C语言使用尾插法建立带头结点的单链表
时间: 2023-05-30 17:02:29 浏览: 143
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createLinkedList(); // 创建链表
void printLinkedList(LinkedList list); // 打印链表
void freeLinkedList(LinkedList list); // 释放链表
int main() {
LinkedList list = createLinkedList();
printLinkedList(list);
freeLinkedList(list);
return 0;
}
LinkedList createLinkedList() {
LinkedList head = (LinkedList)malloc(sizeof(Node)); // 创建头结点
head->next = NULL; // 头结点不存放数据
LinkedList tail = head; // tail指向尾结点
int data;
while (scanf("%d", &data) != EOF) {
LinkedList newNode = (LinkedList)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
tail->next = newNode; // 尾结点指向新结点
tail = newNode; // tail指向新的尾结点
}
return head;
}
void printLinkedList(LinkedList list) {
LinkedList p = list->next; // p指向第一个结点
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void freeLinkedList(LinkedList list) {
LinkedList p = list;
while (p != NULL) {
LinkedList q = p->next;
free(p);
p = q;
}
}
```
阅读全文