c 语言输入链表数据(以数字-1作为输入结束的标志),例如建立链表1 2 3 则需输入1 2 3 -1;
时间: 2023-04-10 07:03:41 浏览: 108
可以使用如下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList() {
struct ListNode *head = NULL, *tail = NULL;
int num;
while (scanf("%d", &num) == 1 && num != -1) {
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = num;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
int main() {
struct ListNode *head = createList();
// do something with the linked list
return 0;
}
```
阅读全文