用C语言 实现单链表初始化 插入 删除 清空 遍历
时间: 2024-09-19 20:17:15 浏览: 57
在C语言中,我们可以使用结构体和函数来实现单链表的基本操作,包括初始化、插入、删除和遍历。这里是一个简单的示例:
首先,我们定义一个链表节点结构:
```c
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
} Node;
```
1. **初始化** (创建一个空链表):
```c
void initializeList(Node** head) {
*head = NULL; // 初始化链表头指针为空
}
```
2. **插入** (在链表头部插入元素):
```c
void insertAtBeginning(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
3. **删除** (删除指定值的第一个节点,如果存在):
```c
void deleteElement(Node** head, int value) {
if (*head == NULL) return;
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
}
}
```
4. **清空** (释放链表的所有内存):
```c
void clearList(Node** head) {
Node* current = *head;
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
*head = NULL;
}
```
5. **遍历** (打印链表所有元素):
```c
void traverseList(Node* head) {
Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
```
阅读全文