1. 程式人生 > 實用技巧 >單鏈表具體主要自編函式

單鏈表具體主要自編函式

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 //單鏈表練習
 5 struct Node//定義一個結構體 模板 
 6 {
 7     int data;
 8     struct Node* next;    
 9 } ;
10 struct Node* createlist()//建立新的連結串列 
11 {
12     struct Node* headnode = (struct Node*)malloc(sizeof(struct Node));
13     headnode->next = NULL;
14 return headnode; 15 } 16 17 18 19 struct Node * createnode(int data)//建立新節點 引數:初始值 20 { 21 struct Node* newnode = (struct Node*)malloc(sizeof(struct Node)); 22 newnode->data = data; 23 newnode->next = NULL; 24 return newnode; 25 } 26 27 28 29 30 struct Node * printlist(struct
Node* headNode)//列印連結串列,測試環節 引數:哪個連結串列 31 { 32 struct Node* Pmove = headNode->next; 33 while (Pmove) 34 { 35 printf("%d",Pmove->data); 36 Pmove = Pmove->next; 37 } 38 printf("\n"); 39 } 40 41 42 43 44 void insertNodeByHead(struct Node* headnode,int data)//
創造並頭部插入節點 引數:哪個連結串列,插入節點初始值 45 { 46 struct Node* newnode = createnode(data); 47 newnode->next = headnode->next; 48 headnode->next = newnode; 49 } 50 51 52 53 54 void deleteNode (struct Node* headnode,int posdata)//指定位置刪除節點 引數:目標連結串列,位置資料 55 { 56 struct Node* posnode = headnode->next;//重頭開始尋找 57 struct Node* posnodefront = headnode; 58 if (posnode == NULL) 59 printf("無法刪除,連結串列為空\n"); 60 else 61 { 62 while(posnode->data != posdata) 63 { 64 posnodefront = posnode;//移步向下尋找 65 posnode = posnodefront->next; 66 if (posnode == NULL) 67 { 68 printf("沒有找到相關資訊\n"); 69 return; 70 } 71 } 72 posnodefront ->next = posnode->next;//重組指向 73 free(posnode);//釋放空間 74 } 75 } 76 77 int main() 78 { 79 struct Node* list = createlist(); 80 insertNodeByHead(list,1); 81 insertNodeByHead(list,2); 82 insertNodeByHead(list,3); 83 insertNodeByHead(list,4); 84 printlist(list); 85 return 0; 86 }