创建链表以输入-1结束c语言
时间: 2023-05-26 17:07:06 浏览: 105
c语言链表创建
实现如下:
```c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
int main() {
Node *head = NULL;
Node *tail = NULL;
int num;
scanf("%d", &num);//先读入一个数
while (num != -1) {
Node *node = (Node *)malloc(sizeof(Node));
node->val = num;
node->next = NULL;
if (head == NULL) {//插入第一个节点
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
scanf("%d", &num);//再读入一个数
}
//输出链表
Node *p = head;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
//释放链表内存
p = head;//从头开始释放内存
while (p != NULL) {
Node *q = p;
p = p->next;
free(q);
}
return 0;
}
```
阅读全文