用C语言实现链表
时间: 2023-07-11 10:09:09 浏览: 59
链表是一种常用的数据结构,C语言中可以通过结构体和指针来实现链表。下面是一个简单的链表实现示例,包括链表的创建、插入、删除和遍历操作。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct node {
int data;
struct node *next;
};
// 创建链表
struct node* create_list() {
struct node *head, *p, *q;
int n, i;
printf("请输入链表长度:");
scanf("%d", &n);
head = (struct node*) malloc(sizeof(struct node));
if (!head) {
printf("内存分配失败\n");
exit(1);
}
head->next = NULL;
q = head;
for (i = 0; i < n; i++) {
p = (struct node*) malloc(sizeof(struct node));
if (!p) {
printf("内存分配失败\n");
exit(1);
}
printf("请输入第%d个节点的数据:", i + 1);
scanf("%d", &p->data);
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
// 插入节点
void insert_node(struct node *head, int position, int data) {
struct node *p, *q;
int i = 0;
p = head->next;
while (p && i < position - 1) {
p = p->next;
i++;
}
if (!p || i > position - 1) {
printf("插入位置有误\n");
return;
}
q = (struct node*) malloc(sizeof(struct node));
if (!q) {
printf("内存分配失败\n");
exit(1);
}
q->data = data;
q->next = p->next;
p->next = q;
}
// 删除节点
void delete_node(struct node *head, int position) {
struct node *p, *q;
int i = 0;
p = head->next;
while (p && i < position - 1) {
p = p->next;
i++;
}
if (!p || i > position - 1 || !p->next) {
printf("删除位置有误\n");
return;
}
q = p->next;
p->next = q->next;
free(q);
}
// 遍历链表
void traverse_list(struct node *head) {
struct node *p;
p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 释放链表空间
void free_list(struct node *head) {
struct node *p, *q;
p = head;
while (p) {
q = p->next;
free(p);
p = q;
}
}
int main() {
struct node *head;
int position, data;
head = create_list();
printf("插入节点,请输入插入位置和插入数据:");
scanf("%d %d", &position, &data);
insert_node(head, position, data);
printf("删除节点,请输入删除位置:");
scanf("%d", &position);
delete_node(head, position);
printf("链表内容为:");
traverse_list(head);
free_list(head);
return 0;
}
```
这是一个简单的链表实现,可以根据实际需要进行修改和完善。同时,需要注意链表的内存管理,避免内存泄漏和野指针等问题。