1、 單鏈表的建立、插入、遍歷node
1 // 2 // main.c 3 // 1.1-鏈表建立 4 // 5 // Created by LinKun on 2016/10/14. 6 // Copyright © 2016年 LinKun. All rights reserved. 7 // 8 9 #include <stdio.h> 10 #include <stddef.h> 11 #include <stdlib.h> 12 #include <stdbool.h> 13 14 #define ElemType char 15 16 #pragma mark - 鏈表結點結構 17 typedef struct Node { 18 ElemType data; 19 struct Node *next; 20 }Node; 21 22 #pragma mark - 1. 建立單鏈表 23 Node *CreateList(Node *head) { 24 // 若是頭結點爲空,則建立頭結點 25 if (head == NULL) { 26 head = (Node *)malloc(sizeof(Node)); 27 head->next = NULL; 28 } 29 30 // 指向當前結點 31 Node *prev = head, *temp; 32 ElemType ch; 33 34 while (true) { 35 printf("input node: "); 36 37 scanf("%c", &ch); 38 39 if (ch == '#') 40 break; 41 42 // 建立新鏈表結點 43 temp = (Node *)malloc(sizeof(Node)); 44 temp->data = ch; 45 temp->next = NULL; 46 47 // 在表尾結點後面插入新結點 48 prev->next = temp; 49 prev = temp; 50 51 // 過濾回車鍵 52 getchar(); 53 } 54 55 return head; 56 } 57 58 #pragma mark - 2. 遍歷單鏈表 59 void TranversalList(Node *head) { 60 // 沒有頭結點則直接返回 61 if (head == NULL) { 62 printf("遍歷失敗,鏈表表頭爲空!"); 63 return; 64 } 65 66 // 指向當前結點的下一個結點 67 Node *curr = head->next; 68 69 // 當前結點有下一結點時,輸出下一結點值 70 while (curr) { 71 printf("結點%c->", curr->data); 72 curr = curr->next; 73 74 } 75 printf("NULL\n"); 76 } 77 78 #pragma mark 3. 插入結點 79 Node *InsertNode(Node *head, ElemType element) { 80 if (head == NULL) { 81 printf("插入失敗,鏈表表頭爲空!"); 82 return head; 83 } 84 85 // 指向當前結點 86 Node *prev = head; 87 // 指向當前結點的下一個結點 88 Node *curr = head->next; 89 90 // 遞推到當前結點是鏈表尾結點 91 while (curr) { 92 prev = curr; 93 curr = curr->next; 94 } 95 96 // 建立新結點 97 Node *temp = (Node *)malloc(sizeof(Node)); 98 temp->data = element; 99 temp->next = NULL; 100 101 // 插入到鏈表尾結點以後 102 prev->next = temp; 103 104 return head; 105 } 106 107 108 109 #pragma mark - 測試 110 int main(int argc, const char * argv[]) { 111 112 Node *head; 113 114 // 建立鏈表並遍歷 115 head = CreateList(head); 116 printf("遍歷結果:\n"); 117 TranversalList(head); 118 119 // 插入鏈表元素並遍歷 120 head = InsertNode(head, 'a'); 121 printf("遍歷結果:\n"); 122 TranversalList(head); 123 124 return 0; 125 }