用C语言实现在一个链表中间插入一个节点
以下是用C语言实现在一个链表中间插入一个节点的示例代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(Node* head, int index, int data) {
Node* newNode = createNode(data);
Node* current = head;
int i = 0;
while (i < index - 1 && current != NULL) {
current = current->next;
i++;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
} else {
printf("Index out of range\n");
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(4);
printf("Original list: ");
printList(head);
insertNode(head, 2, 3);
printf("List after inserting 3: ");
printList(head);
return 0;
}
首先,我们定义了一个节点结构体,其中包含数据和下一个节点的指针。然后,我们定义了一个创建节点的函数,以便在需要时创建新节点。接下来,我们定义了一个在链表中插入节点的函数。该函数接收头节点、要插入的节点索引和要插入的数据作为参数。函数使用while循环遍历链表,找到要插入节点的位置。然后,它创建一个新节点,并将其插入链表中。最后,我们定义了一个打印链表的函数,以便在需要时打印链表。
在main函数中,我们首先创建一个包含三个节点的链表,并打印原始链表。然后,我们调用insertNode函数,将一个新节点插入到链表中间。最后,我们再次打印链表,以确保新节点已成功插入
原文地址: http://www.cveoy.top/t/topic/eCG4 著作权归作者所有。请勿转载和采集!