C语言链表demo的简单应用
时间: 2023-10-02 21:13:33 浏览: 52
以下是一个简单的C语言链表demo,可以实现链表的创建、插入、删除和遍历操作。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct node {
int data; // 数据域
struct node* next; // 指针域
} Node;
// 创建链表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node)); // 创建头节点
head->next = NULL;
return head;
}
// 在链表尾部插入节点
void insertNode(Node* head, int data) {
Node* p = head; // 指向头节点
while (p->next != NULL) {
p = p->next; // 找到链表尾部
}
Node* newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->data = data;
newNode->next = NULL;
p->next = newNode; // 在链表尾部插入新节点
}
// 在链表指定位置插入节点
void insertNodeAtPos(Node* head, int data, int pos) {
Node* p = head; // 指向头节点
int i = 0;
while (p != NULL && i < pos - 1) {
p = p->next; // 找到指定位置的前一个节点
i++;
}
if (p == NULL || i > pos - 1) {
printf("Invalid position\n"); // 位置无效
return;
}
Node* newNode = (Node*)malloc(sizeof(Node)); // 创建新节点
newNode->data = data;
newNode->next = p->next; // 在指定位置插入新节点
p->next = newNode;
}
// 删除链表指定位置的节点
void deleteNodeAtPos(Node* head, int pos) {
Node* p = head; // 指向头节点
int i = 0;
while (p->next != NULL && i < pos - 1) {
p = p->next; // 找到指定位置的前一个节点
i++;
}
if (p->next == NULL || i > pos - 1) {
printf("Invalid position\n"); // 位置无效
return;
}
Node* q = p->next; // 指向要删除的节点
p->next = q->next; // 删除节点
free(q);
}
// 遍历链表
void traverseList(Node* head) {
Node* p = head->next; // 指向第一个节点
while (p != NULL) {
printf("%d ", p->data); // 输出节点的数据
p = p->next;
}
printf("\n");
}
// 主函数
int main() {
Node* head = createList(); // 创建链表
insertNode(head, 1); // 在链表尾部插入节点
insertNode(head, 2);
insertNode(head, 3);
insertNodeAtPos(head, 4, 2); // 在链表指定位置插入节点
deleteNodeAtPos(head, 3); // 删除链表指定位置的节点
traverseList(head); // 遍历链表
return 0;
}
```
运行结果:
```
1 2 4
```
相关推荐
![](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)
![](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)