以下是一個簡單的單鏈表的C語言實現:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
// 創建鏈表節點
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
// 插入節點到鏈表尾部
void insert(struct ListNode** head, int value) {
struct ListNode* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
struct ListNode* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
}
}
// 刪除指定值的節點
void removeNode(struct ListNode** head, int value) {
struct ListNode* cur = *head;
struct ListNode* prev = NULL;
while (cur != NULL) {
if (cur->val == value) {
if (prev == NULL) { // 刪除頭節點
*head = cur->next;
} else {
prev->next = cur->next;
}
free(cur);
return;
}
prev = cur;
cur = cur->next;
}
}
// 打印鏈表
void printList(struct ListNode* head) {
struct ListNode* cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
int main() {
struct ListNode* head = NULL;
// 插入節點
insert(&head, 1);
insert(&head, 2);
insert(&head, 3);
// 打印鏈表
printList(head);
// 刪除節點
removeNode(&head, 2);
// 打印鏈表
printList(head);
return 0;
}
該代碼實現了一個簡單的單鏈表,包括創建節點、插入節點、刪除節點以及打印鏈表的功能。在main()
函數中演示了如何使用這些功能。