创建链表以输入-1结束
时间: 2023-05-26 20:07:05 浏览: 132
以下是Python代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def createLinkedList():
head = ListNode()
tail = head
while True:
val = int(input())
if val == -1:
break
node = ListNode(val)
tail.next = node
tail = node
return head.next
if __name__ == "__main__":
linkedList = createLinkedList()
while linkedList:
print(linkedList.val, end=" ")
linkedList = linkedList.next
```
使用时,调用`createLinkedList()`函数即可创建一个带头结点的链表,输入-1时结束。程序会输出创建的链表的值序列。
相关问题
创建链表以输入-1结束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;
}
```
输入链表数据(以数字-1作为输入结束的标志),例如建立链表1 2 3 则需输入1 2 3 -1;
好的,我可以回答这个问题。以下是一个示例代码,可以输入链表数据并创建链表:
```
#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;
}
```