用C语言写一个简单的单链表
时间: 2023-05-18 18:05:45 浏览: 46
以下是一个简单的单链表的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data;
struct node *next;
} Node;
// 创建链表
Node *createList(int n) {
Node *head = NULL, *tail = NULL;
for (int i = 0; i < n; i++) {
Node *newNode = (Node *)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &newNode->data);
newNode->next = NULL;
if (head == NULL) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
// 遍历链表
void traverseList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 插入节点
Node *insertNode(Node *head, int pos, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (pos == 1) {
newNode->next = head;
return newNode;
}
Node *p = head;
for (int i = 1; i < pos - 1; i++) {
p = p->next;
if (p == NULL) {
printf("插入位置无效!\n");
return head;
}
}
newNode->next = p->next;
p->next = newNode;
return head;
}
// 删除节点
Node *deleteNode(Node *head, int pos) {
if (pos == 1) {
Node *p = head;
head = head->next;
free(p);
return head;
}
Node *p = head;
for (int i = 1; i < pos - 1; i++) {
p = p->next;
if (p == NULL) {
printf("删除位置无效!\n");
return head;
}
}
Node *q = p->next;
p->next = q->next;
free(q);
return head;
}
// 销毁链表
void destroyList(Node *head) {
Node *p = head;
while (p != NULL) {
Node *q = p;
p = p->next;
free(q);
}
}
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("创建的链表为:");
traverseList(head);
int pos, value;
printf("请输入要插入的位置和值:");
scanf("%d%d", &pos, &value);
head = insertNode(head, pos, value);
printf("插入节点后的链表为:");
traverseList(head);
printf("请输入要删除的位置:");
scanf("%d", &pos);
head = deleteNode(head, pos);
printf("删除节点后的链表为:");
traverseList(head);
destroyList(head);
return 0;
}
```
该程序实现了链表的创建、遍历、插入、删除和销毁等基本操作。用户可以根据需要自行修改和扩展。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)