链表基础操作2
Posted 暮雨煙深淺
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表基础操作2相关的知识,希望对你有一定的参考价值。
实现线性表的链式存储结构——线性链表。从文件输入
一批整数,建立有序链表(升序),并完成:
查找一个指定元素
插入一个给定元素
删除一个指定元素
统计链表的长度
输出线性链表
实现安逆序链表的重建
#include <iostream> #include<stdio.h> #include<stdlib.h> using namespace std; int readthedata(int a[] ) { FILE * r=fopen("1.txt","r"); int j=0,k=0,temp,x,xp,counter=0; while(fscanf(r,"%d",&a[counter])!=EOF) { counter++; } for(j=0;j<counter;j++) { x=a[j]; xp=j; for(k=j;k<counter;k++) { if(a[k]>x) { x=a[k]; xp = k ; } } temp = x; a[xp] = a[j]; a[j] = temp ; } for(j=0;j<counter;j++) printf("%d",a[j]); //关闭文件 fclose(r); return counter ; } struct node{ int data; node* next ; }; struct node* Create_link(int a[],int n) { int i ; node *p,*pre,*head; //我们一般说知道一个节点的位置,那么这个指针一定是指向这个节点的前一个节点,故pre超级重要 head = new node; head->next = NULL; pre = head; for(i=0;i<n;i++) { p = new node; p->data = a[i]; p->next =NULL; pre->next =p; pre=p; } printf("create successfully!\n"); return head; } void findathing(int a,node *head) { node *p ; int flag = 0; p = head->next ; while(p!=NULL) { if(p->data==a) flag = 1; p = p->next; } if(flag==1) printf("yep,we find it "); else printf("sorry,we can‘t find it"); } void insertadata(node* head,int x) { node *p ,*q ; q = new node ; q->data =x; q->next = NULL; p=head->next; while(p->next!=NULL) p=p->next; p->next = q; printf("insert successfully!\n"); } void deleteadata(node* head ,int x) { node *p ,*q; p=head->next; while(p!=NULL&&p->next->data!=x) p=p->next; if(p==NULL) printf("sorry,there is no such a data"); if(p->next->data==x) { q=p->next; p->next=q->next; delete q; printf("delete successfully!\n"); } } void printalink(node* head) { node* p; p=head->next; while(p!=NULL) { printf("%d\n",p->data); p=p->next; } printf("printf successfully!\n"); } int calculatethedata(node *head) { int counter=0; node *p ; p=head->next; while(p!=NULL) { p=p->next; counter++; } return counter ; } void reversethelink(node *head) { node *p,*q ; p = head->next->next ; head->next->next = NULL; while(p) { q = p->next ; p->next = head->next ; head->next =p ; p=q; } printf("reverse successfullly"); } int main() { int a[100]; node *head ; int n ,i; char ch ; printf("建立_C,插入_I,删除_D,显示_O,查找_F,反向_R,退出_E,统计长度_L\n"); scanf("%c",&ch); while(ch!=‘E‘) { if(ch==‘C‘) { n = readthedata(a); head = Create_link(a,n); } if(ch==‘F‘) { printf("input the data you want to find"); scanf("%d",&i); findathing(i,head); } if (ch==‘I‘) { printf("input the data you want to insert"); scanf("%d",&i); insertadata(head,i); } if(ch==‘D‘) { printf("input the data you want to delete"); scanf("%d",&i); deleteadata(head,i); } if(ch==‘O‘) { printalink(head); } if(ch==‘L‘) { printf("%d",calculatethedata(head)); } if(ch==‘R‘) { reversethelink(head); } printf("建立_C,插入_I,删除_D,显示_O,查找_F,反向_R,退出_E,统计长度_L\n"); scanf("%c",&ch); } }
以上是关于链表基础操作2的主要内容,如果未能解决你的问题,请参考以下文章