1. 程式人生 > >關於無頭結點鏈表的創建算法及基礎功能打的實現

關於無頭結點鏈表的創建算法及基礎功能打的實現

play temp 三方 頭指針 type malloc turn 元素 info

  技術分享圖片

這裏是無頭結點的鏈表創建:


1
#include<stdio.h> 2 #include<stdlib.h> 3 typedef struct Link 4 { 5 int data; 6 struct Link *next; 7 }lk;//定義lk為struct link類型; 8 9 lk *initlink()//鏈表的建立,返回值為lk類型的指針; 10 { 11 int i,n; 12 lk *head=(lk*)malloc(sizeof(lk));//先用頭指針head申請一段內存
13 lk *temp=head; 14 printf("請你輸入你要的十個數字:\n"); 15 for(i=0;i<10;i++) 16 { 17 lk *a=(lk*)malloc(sizeof(lk));//開始申請結點,每個結點包含數據域和指針域; 18 scanf("%d",&n); 19 a->data=n;//使第一個結點接收數據; 20 a->next=NULL; 21 temp->next=a;//這裏的temp相當於是第三個輔助用的結點,用來遞增遍歷輸入元素;
22 temp=temp->next; 23 24 } 25 return head; 26 } 27 28 void display(lk *head) 29 { 30 lk *temp=head; 31 while(temp->next)//因為此算法是沒有頭節點的,所以要從頭指針指向的下一個結點開始,而不是temp; 32 { 33 temp=temp->next; 34 printf("%d ",temp->data);
35 } 36 printf("\n"); 37 } 38 39 lk *insertdata(lk *head,int data,int add) 40 { 41 int i; 42 lk *temp=head; 43 for(i=1;i<add;i++) 44 { 45 if(temp==NULL) 46 { 47 printf("位置無效\n"); 48 return head; 49 } 50 temp=temp->next; 51 }//一直將temp移動到要插入的那個位置的前一個結點; 52 53 lk *c=(lk*)malloc(sizeof(lk));//創造第三方指針接受新數據; 54 c->data=data; 55 c->next=temp->next; 56 temp->next=c;//要先讓c的指針域指向插入的指針,再將c和上一個結點連起來; 57 return head; 58 } 59 60 lk *deldata(lk *head,int add) 61 { 62 int i; 63 lk *temp=head; 64 for(i=1;i<add;i++) 65 { 66 temp=temp->next; 67 } 68 lk *d=temp->next; 69 temp->next=temp->next->next; 70 free(d);//讓d記錄剛才的數據防止丟失,然後再釋放內存; 71 return head; 72 } 73 int chazhao(lk *head,int data) 74 { 75 lk *e=head; 76 int i; 77 i=1; 78 while(e->next) 79 { 80 e=e->next; 81 if(e->data==data) 82 { 83 return i; 84 } 85 i++; 86 } 87 return -1; 88 } 89 90 int main() 91 { 92 int weizhi,shuzi; 93 int t,m; 94 lk *p; 95 printf("這個程序你要玩幾遍勒?\n輸入他:"); 96 scanf("%d",&m); 97 while(m--) 98 { 99 printf("歡迎使用邱哥的程序\n"); 100 p=initlink(); 101 display(p); 102 103 printf("輸入你要在第幾個位置插入數字幾:\n"); 104 scanf("%d %d",&weizhi,&shuzi); 105 insertdata(p,shuzi,weizhi); 106 display(p); 107 108 printf("輸入你要刪除第幾個位置的元素:\n"); 109 scanf("%d",&weizhi); 110 deldata(p,weizhi); 111 display(p); 112 113 printf("輸入你要查找的數字:\n"); 114 scanf("%d",&shuzi); 115 t=chazhao(p,shuzi); 116 if(t==-1) 117 printf("不好意思,沒有找到\n"); 118 else 119 printf("它的位置在第%d個。\n",t); 120 printf("謝謝使用\n"); 121 } 122 123 return 0; 124 }

關於無頭結點鏈表的創建算法及基礎功能打的實現