標籤:style io ar for 資料 art div 代碼 sp
線性表的鏈式儲存結構——鏈表,包含單鏈表、雙鏈表、迴圈鏈表等。單鏈表的結點由資料元素和指向下一個結點的指標構成,是最簡單的一種鏈表結構。
對單鏈表的操作非常多,如尋找、插入、刪除、逆置、列印等,現對這些操作的實現做一個小結,代碼用C語言實現。
#include<stdio.h>#include<stdlib.h>typedef struct LNode{char data;struct LNode *next;}LinkList;extern LinkList *CreatListF();//頭插法extern LinkList *CreatListE();//尾插法extern int LocateList(LinkList *head, char e);//尋找結點extern LinkList *InsertList(LinkList *&head, int i, char e);//插入結點extern LinkList *DeleteList(LinkList *&head, int i, char &e);//刪除結點extern int LengthList(LinkList *head);//計算鏈表的長度extern void PrintList(LinkList *head);//列印鏈表extern LinkList *ReverseList(LinkList *&head);//逆置鏈表LinkList *CreatListF(){LinkList *head,*p;char str[10];int i;head=(LinkList *)malloc(sizeof(LinkList));head->next=NULL;printf("please input a string:");gets(str);for(i=0;str[i]!='\0';i++){p=(LinkList *)malloc(sizeof(LinkList));p->data=str[i];p->next=head->next;head->next=p;}return head;}LinkList *CreatListE(){LinkList *head,*p,*q;char str[10];int i;head=(LinkList *)malloc(sizeof(LinkList));head->next=NULL;q=head;printf("please input a string:");gets(str);for(i=0;str[i]!='\0';i++){p=(LinkList *)malloc(sizeof(LinkList));p->data=str[i];q->next=p;q=p;}q->next=NULL;return head;} int LocateList(LinkList *head, char e){LinkList *p=head->next;int i=1;while(p!=NULL && p->data != e){p=p->next;i++;}if(NULL==p){printf("NO Found Node\n");return 0;}elsereturn i;}LinkList *InsertList(LinkList *&head, int i, char e){LinkList *p,*q;int j=0;p=head;while(j<i-1 && p!=NULL){j++;p=p->next;}if(NULL==p){printf("No Found Node %d!\n",i);exit(0);}q=(LinkList *)malloc(sizeof(LinkList));q->data=e;q->next=p->next;p->next=q;return head;}LinkList *DeleteList(LinkList *&head, int i, char &e){LinkList *p,*q;int j=0;p=head;while(j<i-1 && p!=NULL){j++;p=p->next;}if(NULL==p){printf("No Found Node %d!\n",i);exit(0);}else{q=p->next;if(NULL==q){printf("NO Found");exit(0);}e=q->data;p->next=q->next;free(q);return head;}}int LengthList(LinkList *head){LinkList *p;int n=0;p=head->next;while(p!=NULL){++n;p=p->next;}return n;}void PrintList(LinkList *head){LinkList *p;p=head->next;while(p){printf("%c",p->data);p=p->next;}printf("\n");}LinkList *ReverseList(LinkList *&head){LinkList *p,*q;if(head->next && head->next->next)//鏈表不為空白或單結點{p=head->next;q=p->next;p>next-=NULL;//將結點變成終端結點while(q!=NULL){p=q;q=q->next;p->next=head->next;head->next=p;}return head;}return head;//假設是空表或單結點表,直接返回head}
單鏈表的運算實現