c语言以函数形式实现单链表的建立、插入、删除、查找运算。
时间: 2023-12-04 12:10:51 浏览: 30
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct node {
int data;
struct node* next;
};
// 建立链表
struct node* create_list() {
struct node* head = NULL;
struct node* tail = NULL;
int data;
printf("请输入节点的值,以-1结束:");
while (1) {
scanf("%d", &data);
if (data == -1) {
break;
}
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
}
return head;
}
// 插入节点
void insert_node(struct node* head, int pos, int data) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->next = NULL;
if (pos == 1) {
new_node->next = head;
head = new_node;
} else {
struct node* p = head;
for (int i = 1; i < pos - 1; ++i) {
p = p->next;
}
new_node->next = p->next;
p->next = new_node;
}
printf("插入节点成功\n");
}
// 删除节点
void delete_node(struct node* head, int pos) {
if (pos == 1) {
struct node* p = head;
head = p->next;
free(p);
} else {
struct node* p = head;
for (int i = 1; i < pos - 1; ++i) {
p = p->next;
}
struct node* q = p->next;
p->next = q->next;
free(q);
}
printf("删除节点成功\n");
}
// 查找节点
int search_node(struct node* head, int data) {
int pos = 0;
struct node* p = head;
while (p != NULL) {
pos++;
if (p->data == data) {
return pos;
}
p = p->next;
}
return -1;
}
// 打印链表
void print_list(struct node* head) {
struct node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
struct node* head = create_list();
print_list(head);
insert_node(head, 3, 10);
print_list(head);
delete_node(head, 2);
print_list(head);
int pos = search_node(head, 10);
printf("节点10的位置是:%d\n", pos);
return 0;
}