引言链表是数据结构中的一个重要组成部分,尤其在C语言编程中,它提供了动态内存分配和灵活的数据组织方式。谭浩强老师的《C程序设计》中详细介绍了链表的相关知识,本文将基于谭浩强老师的讲解,结合实际代码示例...
链表是数据结构中的一个重要组成部分,尤其在C语言编程中,它提供了动态内存分配和灵活的数据组织方式。谭浩强老师的《C程序设计》中详细介绍了链表的相关知识,本文将基于谭浩强老师的讲解,结合实际代码示例,帮助读者轻松掌握链表精髓。
链表是一种线性表,它由一系列结点(Node)组成,每个结点包含数据和指向下一个结点的指针。链表分为单向链表、双向链表和循环链表等。
typedef struct Node { int data; struct Node* next;
} Node;Node* createList(int* arr, int n) { Node* head = NULL; Node* tail = NULL; for (int i = 0; i < n; i++) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = arr[i]; newNode->next = NULL; if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } } return head;
}void printList(Node* head) { Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n");
}Node* findNode(Node* head, int key) { Node* current = head; while (current != NULL && current->data != key) { current = current->next; } return current;
}typedef struct Node { int data; struct Node* next; struct Node* prev;
} Node;Node* createDoublyList(int* arr, int n) { Node* head = NULL; Node* tail = NULL; for (int i = 0; i < n; i++) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = arr[i]; newNode->next = NULL; newNode->prev = NULL; if (head == NULL) { head = newNode; tail = newNode; } else { tail->next = newNode; newNode->prev = tail; tail = newNode; } } return head;
}void printDoublyList(Node* head) { Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n");
}void printReverseDoublyList(Node* head) { Node* current = head; while (current->next != NULL) { current = current->next; } while (current != NULL) { printf("%d ", current->data); current = current->prev; } printf("\n");
}typedef struct Node { int data; struct Node* next;
} Node;Node* createCircularList(int* arr, int n) { Node* head = NULL; Node* tail = NULL; for (int i = 0; i < n; i++) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = arr[i]; newNode->next = NULL; if (head == NULL) { head = newNode; } else { tail->next = newNode; } tail = newNode; } tail->next = head; // 形成循环 return head;
}void printCircularList(Node* head) { Node* current = head; do { printf("%d ", current->data); current = current->next; } while (current != head); printf("\n");
}通过以上对单向链表、双向链表和循环链表的介绍,结合谭浩强老师的讲解和实际代码示例,相信读者已经对链表有了深入的理解。在实际编程中,链表的应用非常广泛,熟练掌握链表的相关知识将有助于提高编程技能。