用c语言创建链表,编写程序实现在指定位置插入,删除,修改节点,并返回原来节点的值
时间: 2024-04-17 13:24:31 浏览: 64
链表程序插入,删除等操作 c语言
好的,下面是一个用 C 语言创建链表并实现插入、删除和修改节点的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表
Node* createList() {
Node* head = NULL; // 头节点
Node* tail = NULL; // 尾节点
int num;
printf("输入链表节点的值(输入-1结束):\n");
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 在指定位置插入节点
void insertNode(Node** head, int position, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
if (position == 0) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
int i = 0;
while (i < position - 1 && current != NULL) {
current = current->next;
i++;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
} else {
printf("插入位置无效!\n");
free(newNode);
}
}
}
// 删除指定位置的节点
void deleteNode(Node** head, int position) {
if (*head == NULL) {
printf("链表为空,无法删除节点!\n");
return;
}
Node* temp = *head;
if (position == 0) {
*head = (*head)->next;
free(temp);
} else {
Node* current = *head;
int i = 0;
while (i < position - 1 && current != NULL) {
current = current->next;
i++;
}
if (current != NULL && current->next != NULL) {
temp = current->next;
current->next = temp->next;
free(temp);
} else {
printf("删除位置无效!\n");
}
}
}
// 修改指定位置的节点值
void modifyNode(Node* head, int position, int value) {
Node* current = head;
int i = 0;
while (i < position && current != NULL) {
current = current->next;
i++;
}
if (current != NULL) {
current->data = value;
} else {
printf("修改位置无效!\n");
}
}
// 打印链表
void printList(Node* head) {
printf("链表的值为:");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// 主函数
int main() {
Node* head = createList();
printList(head);
int position, value;
printf("输入要插入的位置和值:\n");
scanf("%d %d", &position, &value);
insertNode(&head, position, value);
printList(head);
printf("输入要删除的位置:\n");
scanf("%d", &position);
deleteNode(&head, position);
printList(head);
printf("输入要修改的位置和值:\n");
scanf("%d %d", &position, &value);
modifyNode(head, position, value);
printList(head);
return 0;
}
```
这个程序首先会创建一个链表,然后根据用户的输入执行插入、删除和修改节点的操作,并打印每次操作后链表的值。请根据自己的需要进行修改和扩展。希望对你有帮助!
阅读全文