C筆記 #01# 線性錶鏈式儲存——單鏈表
阿新 • • 發佈:2020-08-16
不採用頭結點:
#include <stdio.h> // printf #include <stdbool.h> // bool true false #include <stdlib.h> // malloc EXIT_FAILURE EXIT_SUCCESS struct node { int value; struct node *next; }; // 頭插法,時間複雜度O(1) struct node *add_to_list(struct node *list, int n) { struct node *new_node; new_node= malloc(sizeof(struct node)); if (new_node == NULL) { printf("Error: malloc failed in add_to_list\n"); exit(EXIT_FAILURE); } new_node->value = n; new_node->next = list; return new_node; } // 按值查詢表結點,時間複雜度O(n) struct node *get_by_value(struct node *list, int n) {while (list != NULL && list->value != n) list = list->next; return list; } // 按序號查詢表結點,時間複雜度O(n) struct node *get_by_position(struct node *list, int pos) { if (pos < 1) return NULL; int cur = 1; while (list != NULL && cur < pos) { list = list->next; cur++; } return list; } void print_list(struct node *list) { printf("linked list: "); while (list != NULL) { printf("%d ", list->value); list = list->next; } printf("\n"); } int main() { struct node *first = NULL; first = add_to_list(first, 10); first = add_to_list(first, 20); first = add_to_list(first, 30); first = add_to_list(first, 40); print_list(first); // => 40 30 20 10 printf("%d\n", get_by_value(first, 10)->value); // => 10 printf("%d\n", get_by_position(first, 3)->value); // => 20 // 刪除第3個結點 struct node *p = get_by_position(first, 3 - 1); p->next = (p->next)->next; print_list(first); // => 40 30 10 // 刪除第1個結點 first = first->next; print_list(first); // => 30 10 // 無頭結點的單鏈表,操作第1個結點往往需要“特殊處理”。 return 0; }
引入頭節點的好處是:便於處理首個數據元素。