用c语音实现单链表的运行
时间: 2024-05-06 22:20:09 浏览: 6
以下是单链表的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点
typedef struct node {
int data; // 数据域
struct node *next; // 指针域
} Node, *LinkedList;
// 初始化链表
void initList(LinkedList *list) {
*list = NULL;
}
// 判断链表是否为空
int isListEmpty(LinkedList list) {
return list == NULL;
}
// 在链表头部插入结点
void insertHead(LinkedList *list, int data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->next = *list;
*list = node;
}
// 在链表尾部插入结点
void insertTail(LinkedList *list, int data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (*list == NULL) {
*list = node;
} else {
Node *last = *list;
while (last->next != NULL) {
last = last->next;
}
last->next = node;
}
}
// 删除链表中的结点
void deleteNode(LinkedList *list, int data) {
if (*list != NULL) {
Node *prev = NULL;
Node *curr = *list;
while (curr != NULL) {
if (curr->data == data) {
if (prev == NULL) {
*list = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
break;
}
prev = curr;
curr = curr->next;
}
}
}
// 打印链表
void printList(LinkedList list) {
if (list != NULL) {
Node *node = list;
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
} else {
printf("The list is empty.\n");
}
}
int main() {
LinkedList list;
initList(&list);
printf("Insert node into head:\n");
insertHead(&list, 1);
insertHead(&list, 2);
insertHead(&list, 3);
printList(list);
printf("Insert node into tail:\n");
insertTail(&list, 4);
insertTail(&list, 5);
insertTail(&list, 6);
printList(list);
printf("Delete node with data 3:\n");
deleteNode(&list, 3);
printList(list);
return 0;
}
```
运行结果:
```
Insert node into head:
3 2 1
Insert node into tail:
3 2 1 4 5 6
Delete node with data 3:
2 1 4 5 6
```