c语言编写程序,实现链表的创建、插入和删除等基本操作算法
时间: 2024-03-20 16:40:19 浏览: 15
好的,下面是一个简单的C语言程序,实现链表的创建、插入和删除等基本操作法:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
typedef struct node Node;
Node* create_list(int n) {
Node *head = NULL, *p = NULL, *tail = NULL;
int i, x;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值: ", i + 1);
scanf("%d", &x);
p = (Node*)malloc(sizeof(Node));
p->data = x;
p->next = NULL;
if (head == NULL) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
Node* insert_node(Node* head, int pos, int value) {
Node *p = NULL, *new_node = NULL;
int i;
if (pos < 1) {
printf("插入位置无效!\n");
return head;
}
new_node = (Node*)malloc(sizeof(Node));
new_node->data = value;
new_node->next = NULL;
if (pos == 1) {
new_node->next = head;
head = new_node;
} else {
p = head;
for (i = 1; i < pos - 1 && p != NULL; i++) {
p = p->next;
}
if (p == NULL) {
printf("插入位置无效!\n");
return head;
}
new_node->next = p->next;
p->next = new_node;
}
return head;
}
Node* delete_node(Node* head, int pos) {
Node *p = NULL, *temp = NULL;
int i;
if (pos < 1) {
printf("删除位置无效!\n");
return head;
}
if (pos == 1) {
temp = head;
head = head->next;
free(temp);
} else {
p = head;
for (i = 1; i < pos - 1 && p != NULL; i++) {
p = p->next;
}
if (p == NULL || p->next == NULL) {
printf("删除位置无效!\n");
return head;
}
temp = p->next;
p->next = temp->next;
free(temp);
}
return head;
}
void print_list(Node* head) {
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n, pos, value;
Node* head = NULL;
printf("请输入链表的长度: ");
scanf("%d", &n);
head = create_list(n);
print_list(head);
printf("请输入要插入的位置和值: ");
scanf("%d%d", &pos, &value);
head = insert_node(head, pos, value);
print_list(head);
printf("请输入要删除的位置: ");
scanf("%d", &pos);
head = delete_node(head, pos);
print_list(head);
return 0;
}
```
这个程序在上面创建链表的基础上,实现了链表的插入和删除功能。具体操作如下:
- `insert_node` 函数用于在链表的指定位置插入一个新节点。它接收三个参数,分别是链表的头指针、插入位置和新节点的值。如果插入位置无效,则不做任何操作,直接返回原来的头指针。否则,在指定位置插入新节点,并返回新的头指针。
- `delete_node` 函数用于删除链表的指定位置的节点。它接收两个参数,分别是链表的头指针和要删除的位置。如果删除位置无效,则不做任何操作,直接返回原来的头指针。否则,删除指定位置的节点,并返回新的头指针。
- `print_list` 函数用于打印链表的所有节点的值。
在 `main` 函数中,我们先调用 `create_list` 函数创建链表,并打印出来。然后让用户输入要插入的位置和值,调用 `insert_node` 函数在指定位置插入新节点,并打印出来。最后让用户输入要删除的位置,调用 `delete_node` 函数删除指定位置的节点,并打印出来。