單鏈表的基本操作 增刪查以及 頭插法尾插法建表(初學)
阿新 • • 發佈:2018-12-13
需要注意的:1.InitList(List &L)&是識別符號的作用 L和實參同一個引用 2.在每個方法中不能對頭結點操作 先把頭結點賦值一份 對副本引用操作 3.操作連結串列中間需要從頭結點開始一個個查詢,找到目標再插入 刪除 可以先寫查詢方法 實現程式碼複用
#include <stdio.h> #include <stdlib.h> typedef struct LNode{ int data; LNode* next; }*LinkList,*List; void CreateLinkList_head(LinkList &l,int n){ //n可以設定為插入結點次數 List p; //l頭結點 p為新結點 int i=0,x; printf("請輸入第%d個結點的值\n",++i); scanf("%d",&x); while(x!=-1){ p=(List)malloc(sizeof(LNode)); // 頭插法 p->next=l->next; //新結點指向原結點指向的 p->data=x; //新結點賦值 l->next=p; //原結點和新結點建立連線 printf("請輸入第%d個結點的值\n",++i); scanf("%d",&x); } } void CreateLinkList_end(LinkList &e,int n){ List l,newList; int i=1,x; l=e; while(n>0){ newList=(List)malloc(sizeof(LNode)); l->next=newList; l=newList; printf("請輸入第%d個結點的值\n",i++); scanf("%d",&x); newList->data=x; n--; } l->next=NULL; } void initLinkList(LinkList &p){ p=(List)malloc(sizeof(LNode)); p->next=NULL; } void DestroyList(LinkList &l){ List p=l->next; while(l->next!=NULL){ l=l->next; free(p); } free(l); //釋放頭結點 l=NULL; //把連結串列首地址賦空 } void ClearList(LinkList &l){ List p=l->next; while(l->next!=NULL){ l=l->next; free(p); } } int LenghtList(LinkList &l){ int i=0; LinkList h; h=l; while(h->next!=NULL){ h=h->next; i++; } return i; } List LocateList(LinkList &l,int n){ //找到第n個元素 返回他的地址 List h; h=l; while(n){ h=h->next; //在第n次迴圈完 h指向第n個元素 n--; } return h; } void InsertList(LinkList &l,int n,int x){ //在第n個位置之後 插入 值x List h,p; p=(List)malloc(sizeof(LNode)); p->data=x; h=l; if(n>LenghtList(l)){ printf("ERROR!"); return; } // while(n){ // h=h->next; // n--; // } //經過n次迴圈 h是第n個結點的地址 h=LocateList(l,n); //找到第n個結點 程式碼複用 p->next=h->next; h->next=p; } void DeleteList(LinkList &l,int n){ List h,p; h=l; if(n>LenghtList(l)){ printf("ERROR!"); return ; } // while(n-1){ // h=h->next; // n--; //經過n-1次迴圈 h是n前一個結點的地址 // } h=LocateList(l,n-1); p=h->next; //要刪除的結點地址 設定p原因:改變指標後用p找到 h->next=p->next; p->next=NULL; free(p); } int main(){ LinkList L,p; initLinkList(L); CreateLinkList_end(L,5); DeleteList(L,4); InsertList(L,3,-1); p=LocateList(L,3); int i=1; while(L->next!=NULL){ L=L->next; printf("第%d個結點的值為%d\n",i++,(L->data)); } printf("%d",p->data); return 0; }