952: c语言单链表的插入操作的实现
时间: 2023-10-03 09:05:53 浏览: 60
单链表的插入操作可以分为两种情况:
1. 在链表头部插入新节点
2. 在链表中间或尾部插入新节点
以下是两种情况的代码实现:
1. 在链表头部插入新节点
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* insertNodeAtBeginning(struct ListNode* head, int val) {
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->val = val;
new_node->next = head;
head = new_node;
return head;
}
int main() {
struct ListNode* head = NULL;
head = insertNodeAtBeginning(head, 1);
head = insertNodeAtBeginning(head, 2);
head = insertNodeAtBeginning(head, 3);
printf("The linked list is: ");
while(head != NULL) {
printf("%d ", head->val);
head = head->next;
}
return 0;
}
```
2. 在链表中间或尾部插入新节点
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* insertNodeAtPosition(struct ListNode* head, int val, int position) {
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->val = val;
new_node->next = NULL;
if (position == 1) {
new_node->next = head;
head = new_node;
return head;
}
struct ListNode* temp = head;
for (int i = 1; i < position-1; i++) {
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
return head;
}
int main() {
struct ListNode* head = NULL;
head = insertNodeAtPosition(head, 1, 1);
head = insertNodeAtPosition(head, 2, 2);
head = insertNodeAtPosition(head, 3, 3);
head = insertNodeAtPosition(head, 4, 2);
printf("The linked list is: ");
while(head != NULL) {
printf("%d ", head->val);
head = head->next;
}
return 0;
}
```