输入链表数据(以数字-1作为输入结束的标志),例如建立链表1 2 3 则需输入1 2 3 -1;
时间: 2023-04-12 09:01:50 浏览: 64
数据链表的建立
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是一个示例代码,可以输入链表数据并创建链表:
```
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList() {
struct ListNode *head = NULL;
struct ListNode *tail = NULL;
int num;
while (1) {
scanf("%d", &num);
if (num == -1) {
break;
}
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = num;
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
int main() {
struct ListNode *head = createList();
struct ListNode *p = head;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
return 0;
}
```
阅读全文