用数据结构写一个函数,实现输出带头结点的单链表的的所有结点元素值
时间: 2023-05-27 09:06:39 浏览: 126
下面是用 C 语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
// 初始化链表
LinkedList initLinkedList() {
Node *head = (Node *)malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 输出链表所有结点元素值
void printLinkedList(LinkedList head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkedList list = initLinkedList();
Node *p1 = (Node *)malloc(sizeof(Node));
p1->data = 1;
p1->next = NULL;
list->next = p1;
Node *p2 = (Node *)malloc(sizeof(Node));
p2->data = 2;
p2->next = NULL;
p1->next = p2;
Node *p3 = (Node *)malloc(sizeof(Node));
p3->data = 3;
p3->next = NULL;
p2->next = p3;
printLinkedList(list);
return 0;
}
```
运行结果:
```
1 2 3
```
阅读全文