编写一个函数,实现在链表中给定位置插入,删除的结果链表
时间: 2023-05-11 18:06:56 浏览: 44
非常好的问题!以下是一个示例函数,可以实现在链表中给定位置插入和删除节点的功能:
```
typedef struct Node {
int data;
struct Node* next;
} Node;
void insertNode(Node** head, int position, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (position == 0) {
newNode->next = *head;
*head = newNode;
return;
}
Node* current = *head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL) {
printf("Invalid position\n");
return;
}
newNode->next = current->next;
current->next = newNode;
}
void deleteNode(Node** head, int position) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
Node* temp = *head;
if (position == 0) {
*head = temp->next;
free(temp);
return;
}
Node* current = *head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
current = current->next;
}
if (current == NULL || current->next == NULL) {
printf("Invalid position\n");
return;
}
temp = current->next;
current->next = temp->next;
free(temp);
}
```
这个函数使用了一个链表结构体,其中包含一个整数数据和一个指向下一个节点的指针。`insertNode`函数可以在链表的任意位置插入一个新节点,而`deleteNode`函数可以删除链表中的任意节点。这些函数都需要传入一个指向链表头节点的指针,以便在链表中进行插入和删除操作。