c语言完成单链表的五个基本操作: 创建链表 销毁链表 在链表的最前面插入元素 在链表的最后面插入元素 判断链表是否为空
时间: 2024-03-13 14:39:01 浏览: 152
以下是C语言完成单链表的五个基本操作的代码和解释:
1. 创建链表
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createList(int n) {
struct Node *head, *p, *q;
int i;
head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;
q = head;
for (i = 0; i < n; i++) {
p = (struct Node*)malloc(sizeof(struct Node));
scanf("%d", &p->data);
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
```
解释:首先定义了一个结构体Node,包含数据域data和指针域next。createList函数用于创建链表,参数n表示链表中节点的个数。首先创建头节点head,并将其next指针置为NULL。然后用q指针指向头节点,循环n次,每次创建一个新节点p,输入数据并将其next指针置为NULL,将q的next指针指向p,再将q指向p,最后返回头节点head。
2. 销毁链表
```c
void destroyList(struct Node* head) {
struct Node* p = head;
while (p != NULL) {
head = head->next;
free(p);
p = head;
}
}
```
解释:destroyList函数用于销毁链表,参数head为头节点。首先定义一个指针p指向头节点,循环遍历链表,每次将head指向下一个节点,释放p所指向的节点,再将p指向head,直到p指向NULL。
3. 在链表的最前面插入元素
```c
struct Node* insertAtBeginning(struct Node* head, int data) {
struct Node* p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = head;
head = p;
return head;
}
```
解释:insertAtBeginning函数用于在链表的最前面插入元素,参数head为头节点,data为要插入的数据。首先创建一个新节点p,将其data域赋值为data,将其next指针指向head,再将head指向p,最后返回头节点head。
4. 在链表的最后面插入元素
```c
struct Node* insertAtEnd(struct Node* head, int data) {
struct Node* p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = NULL;
if (head == NULL) {
head = p;
} else {
struct Node* q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = p;
}
return head;
}
```
解释:insertAtEnd函数用于在链表的最后面插入元素,参数head为头节点,data为要插入的数据。首先创建一个新节点p,将其data域赋值为data,将其next指针置为NULL。如果head为NULL,即链表为空,将head指向p;否则,定义一个指针q指向head,循环遍历链表,直到q的next指针为NULL,将q的next指针指向p,最后返回头节点head。
5. 判断链表是否为空
```c
int isEmpty(struct Node* head) {
return head == NULL;
}
```
解释:isEmpty函数用于判断链表是否为空,参数head为头节点。如果head为NULL,即链表为空,返回1;否则,返回0。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)