如何在C语言中从头开始构建链表,并详细展示创建、插入、删除和遍历节点的代码实现?
时间: 2024-11-16 10:29:14 浏览: 27
在C语言中创建链表是一个基础且重要的数据结构操作。为了实现这一过程,首先需要定义链表的数据结构。根据你提供的辅助资料,我们将按照以下步骤进行:
参考资源链接:[C语言详解:通用链表基础操作及实例](https://wenku.csdn.net/doc/7ai1dn54ei?spm=1055.2569.3001.10343)
1. **定义数据结构**:
- 定义 `EleType` 结构体,包含两个整型成员 `a` 和 `b`。
- 定义 `ChainNode` 结构体,包含 `EleType data` 和指向下一个节点的指针 `next`。
- 定义 `List` 结构体,包含指向链表头部的指针 `head`。
2. **链表操作函数实现**:
- **创建链表**:
```c
List* CreateList() {
List* lp = (List*)malloc(sizeof(List));
if(lp) {
lp->head = NULL;
}
return lp;
}
```
- **销毁链表**:
```c
void DestroyList(List* lp) {
ClearList(lp);
free(lp);
}
```
- **清除链表**:
```c
void ClearList(List* lp) {
ChainNode* current = lp->head;
ChainNode* temp;
while (current != NULL) {
temp = current;
current = current->next;
free(temp);
}
lp->head = NULL;
}
```
- **链表尾部添加节点**:
```c
void ListAppend(List* lp, EleType data) {
ChainNode* newNode = NewChainNode(data);
if (lp->head == NULL) {
lp->head = newNode;
} else {
ChainNode* current = lp->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
```
- **链表指定位置插入节点**:
```c
int ListInsert(List* lp, int pos, EleType data) {
if (pos < 0) return 0;
ChainNode* newNode = NewChainNode(data);
if (pos == 0) {
newNode->next = lp->head;
lp->head = newNode;
return 1;
}
ChainNode* current = lp->head;
for (int i = 0; current != NULL && i < pos - 1; i++) {
current = current->next;
}
if (current == NULL) {
free(newNode);
return 0;
}
newNode->next = current->next;
current->next = newNode;
return 1;
}
```
- **链表指定位置删除节点**:
```c
int ListDelete(List* lp, int pos) {
if (pos < 0 || lp->head == NULL) return 0;
ChainNode* temp;
if (pos == 0) {
temp = lp->head;
lp->head = lp->head->next;
free(temp);
return 1;
}
ChainNode* current = lp->head;
for (int i = 0; current != NULL && i < pos - 1; i++) {
current = current->next;
}
if (current == NULL || current->next == NULL) {
return 0;
}
temp = current->next;
current->next = temp->next;
free(temp);
return 1;
}
```
- **遍历链表**:
```c
void TraverseList(List* lp, void (*f)(EleType*)) {
ChainNode* current = lp->head;
while (current != NULL) {
f(&(current->data));
current = current->next;
}
}
```
- **获取链表指定位置节点的地址**:
```c
ChainNode* GetAddr(List* lp, int pos) {
ChainNode* current = lp->head;
for (int i = 0; current != NULL && i < pos; i++) {
current = current->next;
}
return current;
}
```
- **创建新链表节点**:
```c
ChainNode* NewChainNode(EleType data) {
ChainNode* newNode = (ChainNode*)malloc(sizeof(ChainNode));
if(newNode) {
newNode->data = data;
newNode->next = NULL;
}
return newNode;
}
```
以上代码片段展示了如何在C语言中实现一个基本的单向链表及其操作。务必注意在进行节点删除或链表销毁时正确地管理内存,避免内存泄漏或野指针错误。
参考资源链接:[C语言详解:通用链表基础操作及实例](https://wenku.csdn.net/doc/7ai1dn54ei?spm=1055.2569.3001.10343)
阅读全文