用C语言设计头插法建立带头结点的单链表的函数
时间: 2023-11-07 11:05:03 浏览: 60
以下是用C语言设计头插法建立带头结点的单链表的函数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct List {
Node *head;
Node *tail;
int length;
} List;
List *createList() {
List *list = (List*) malloc(sizeof(List));
Node *head = (Node*) malloc(sizeof(Node));
head->next = NULL;
list->head = head;
list->tail = head;
list->length = 0;
return list;
}
void insert(List *list, int data) {
Node *node = (Node*) malloc(sizeof(Node));
node->data = data;
node->next = list->head->next;
list->head->next = node;
if (list->tail == list->head) {
list->tail = node;
}
list->length++;
}
void printList(List *list) {
Node *node = list->head->next;
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
List *list = createList();
insert(list, 1);
insert(list, 2);
insert(list, 3);
insert(list, 4);
insert(list, 5);
printList(list);
return 0;
}
```
在这个代码中,我们首先定义了两个结构体:`Node`表示节点,`List`表示链表,其中`List`中包含了头结点、尾节点和链表长度。
接下来我们实现了`createList()`函数,用于创建一个空链表,并返回链表的指针。在这个函数中,我们首先分配了链表和头结点的内存空间,然后将头结点的`next`指针指向`NULL`,并将头结点作为链表的头结点和尾节点,最后返回链表的指针。
然后我们实现了`insert()`函数,用于在链表的头部插入一个新节点。在这个函数中,我们首先分配了新节点的内存空间,并将新节点的`data`域赋值为传入的参数`data`,然后将新节点的`next`指针指向头结点的`next`指针所指向的节点,再将头结点的`next`指针指向新节点。如果链表中只有一个节点,那么新节点将成为链表的尾节点。最后,我们将链表的长度加1。
最后我们实现了`printList()`函数,用于打印链表中的所有节点的`data`域。在这个函数中,我们首先定义了一个指向链表头结点的指针`node`,然后不断循环,将`node`指向下一个节点,直到`node`为`NULL`为止。在循环中,我们打印`node`节点的`data`域,并将`node`指向下一个节点。
在`main()`函数中,我们首先创建了一个空链表,然后调用`insert()`函数五次,在链表头部插入了五个节点,最后调用`printList()`函数,打印了链表中所有节点的`data`域。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)