以c语言的形式举例说明链表
时间: 2023-08-15 12:13:36 浏览: 43
下面是一个用 C 语言实现单向链表的简单示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 在链表尾部插入元素
void insertAtEnd(struct Node** head, int value) {
// 创建新节点
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
// 如果链表为空,将新节点设置为头节点
if (*head == NULL) {
*head = newNode;
return;
}
// 遍历链表,找到最后一个节点
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
// 在最后一个节点后插入新节点
current->next = newNode;
}
// 遍历并打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
int main() {
// 初始化链表为空
struct Node* head = NULL;
// 在链表尾部插入元素
insertAtEnd(&head, 1);
insertAtEnd(&head, 2);
insertAtEnd(&head, 3);
// 打印链表
printf("LinkedList: ");
printList(head);
return 0;
}
```
以上代码实现了一个简单的链表,首先定义了一个节点结构 `Node`,包含一个整数数据域 `data` 和一个指向下一个节点的指针 `next`。然后定义了两个函数,`insertAtEnd` 用于在链表尾部插入元素,`printList` 用于遍历并打印链表。
在 `main` 函数中,首先初始化链表为空,然后使用 `insertAtEnd` 函数插入元素 1、2、3 到链表中,最后使用 `printList` 函数打印链表的元素。
运行以上代码,输出结果为:
```
LinkedList: 1 2 3
```
这个例子只是链表的基本操作之一,还可以实现其他常见的链表操作,如在链表头部插入元素、在指定位置删除元素等。