1. 程式人生 > >鏈表基礎操作2

鏈表基礎操作2

結構 位置 stream eof fscanf pen while fop 有序鏈表

實現線性表的鏈式存儲結構——線性鏈表。從文件輸入

一批整數,建立有序鏈表(升序),並完成:

查找一個指定元素

插入一個給定元素

刪除一個指定元素

統計鏈表的長度

輸出線性鏈表

實現安逆序鏈表的重建

#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