C语言指针链表
C语言指针链表是一种非常常见的数据结构,它可以用于在程序中存储和操作一系列相关数据,包括但不限于整数、字符串、结构体等类型。下面我们将介绍如何使用C语言指针链表,并提供一个可以执行的示例代码。
1. 定义链表结构体
链表是由若干个节点组成的,每个节点包含了一个数据元素和一个指向下一个节点的指针。因此,我们需要先定义一个链表节点结构体:
```c
struct node {
int data; // 数据
struct node* next; // 指向下一个节点的指针
};
```
2. 创建链表
创建链表的过程可以通过创建一个头节点来实现。头节点不存储任何数据,只是用于维护整个链表的结构。我们可以定义一个指向头节点的指针:
```c
struct node* head = NULL;
```
3. 插入节点
向链表中插入节点可以通过以下步骤完成:
- 创建一个新节点;
- 将新节点的指针指向下一个
节点;
- 将上一个节点的指针指向新节点。
具体代码如下:```c
void insertNode(int data) {
struct node* newNode = (struct node*) malloc(sizeof(struct node)); // 创建新节点
newNode->data = data; // 设置新节点的数据
newNode->next = NULL; // 将新节点的指针指向NULL
if (head == NULL) { // 如果链表为空,则将头节点指向新节点
head = newNode;
}
else { // 否则在链表末尾插入新节点
struct node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
```
4. 删除节点
从链表中删除节点可以通过以下步骤完成:
- 找到要删除的节点;
- 将上一个节点的指针指向下一个节点;
- 释放要删除的节点的内存空间。
具体代码如下:```c
void deleteNode(int data) {
struct node* current = head;
struct node* previous = NULL;
while (current != NULL) { // 遍历整个链表
if (current->data == data) { // 如果找到要删除的节点
if (previous == NULL) { // 如果要删除的节点是头节点
head = current->next;
}
else { // 否则将上一个节点的指针指向下一个节点
previous->next = current->next;
}
free(current); // 释放要删除的节点的内存空间
return;
}
previous = current;
current = current->next;
}
}
```
5. 遍历链表
遍历链表可以通过定义一个指向头节点的指针,并使用while循环来实现。具体代码如下:
```c
void printList() {
struct node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
```
6. 完整代码
最终的完整代码如下:```c
```
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
void insertNode(int data) {
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else
{
struct node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void deleteNode(int data) {
struct node* current = head;
struct node* previous = NULL;
while (current != NULL) {
if (current->data == data) {
if (previous == NULL) {
head = current->next;
}
else {
previous->next = current->next;
}
free(current);
return;
}
previous = current;
current = current->next;
}
}
void printList() {
struct node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
insertNode(1);
insertNode(2);
insertNode(3);
insertNode(4);
printf("Initial list: ");
printList();
deleteNode(3);
printf("After deleting node with data 3: ");
printList();
return 0;
}
输出结果为:
```
Initial list: 1 2 3 4
After deleting node with data 3: 1 2 4
```
非常好,你已经能够初步了解链表的基本操作了。接下来,你可以尝试用链表实现一些常见的算法,比如反转链表、合并两个有序链表等等,来进一步加深对链表的理解。
有问题评论区见