在编程中,链表的插入操作通常涉及以下几种情况:
在链表头部插入
创建一个新节点`newNode`。
将新节点的`next`指针指向原链表的头节点`head`。
将原链表的头节点`head`指向新节点`newNode`。
在链表中间插入
创建一个新节点`newNode`。
遍历链表,找到需要插入位置的前驱节点`pre`。
将新节点的`next`指针指向前驱节点的下一个节点`pre->next`。
将前驱节点的`next`指针指向新节点`newNode`。
在链表尾部插入
创建一个新节点`newNode`。
遍历链表,找到尾节点(即`next`为`NULL`的节点)。
将尾节点的`next`指针指向新节点`newNode`。
将新节点的`next`指针设置为`NULL`。
```c
include include // 定义链表节点结构体 struct ListNode { int data; struct ListNode *next; }; // 在链表头部插入节点 void insert_head(struct ListNode head, int data) { struct ListNode *newNode = (struct ListNode *)malloc(sizeof(struct ListNode)); if (newNode == NULL) { printf("Memory allocation failed\n"); return; } newNode->data = data; newNode->next = *head; *head = newNode; } // 在链表中间插入节点 void insert_mid(struct ListNode head, int data, int position) { struct ListNode *newNode = (struct ListNode *)malloc(sizeof(struct ListNode)); if (newNode == NULL) { printf("Memory allocation failed\n"); return; } newNode->data = data; newNode->next = NULL; if (*head == NULL) { printf("List is empty\n"); return; } struct ListNode *cur = *head; struct ListNode *pre = NULL; int i = 0; while (cur != NULL && i < position - 1) { pre = cur; cur = cur->next; i++; } if (cur == NULL) { printf("Position out of range\n"); return; } newNode->next = cur->next; cur->next = newNode; if (pre == NULL) { *head = newNode; } } // 在链表尾部插入节点 void insert_tail(struct ListNode head, int data) { struct ListNode *newNode = (struct ListNode *)malloc(sizeof(struct ListNode)); if (newNode == NULL) { printf("Memory allocation failed\n"); return; } newNode->data = data; newNode->next = NULL; if (*head == NULL) { *head = newNode; return; } struct ListNode *cur = *head; while (cur->next != NULL) { cur = cur->next; } cur->next = newNode; } // 打印链表 void print_list(struct ListNode *head) { struct ListNode *cur = head; while (cur != NULL) { printf("%d -> ", cur->data); cur = cur->next; } printf("NULL\n"); } int main() { struct ListNode *head = NULL; insert_head(&head, 1); insert_head(&head, 2); insert_head(&head, 3); insert_mid(&head, 4, 2); insert_tail(&head, 5); print_list(head); return 0; } ``` 在这个示例中,我们定义了一个简单的链表节点结构体`ListNode`,并实现了在链表头部、中间和尾部插入节点的函数。`insert_head`函数用于在链表头部插入节点,`insert_