C语言用尾插法建立单链表,当输入元素为0时停止并输出链表
时间: 2024-05-02 16:21:19 浏览: 121
的所有元素。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
int main() {
Node *head = NULL;
Node *tail = NULL;
int num;
do {
scanf("%d", &num);
if (num == 0) {
break;
}
Node *node = (Node *)malloc(sizeof(Node));
node->data = num;
node->next = NULL;
if (tail == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
} while (1);
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
输入:
```
1 2 3 4 5 6 0
```
输出:
```
1 2 3 4 5 6
```
阅读全文