输入链表数据(以数字-1作为输入结束的标志),例如建立链表1 2 3 则需输入1 2 3 -1;
时间: 2023-04-10 22:03:41 浏览: 52
好的,我可以回答这个问题。以下是输入链表数据的代码示例:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def createLinkedList():
head = ListNode()
cur = head
while True:
val = int(input())
if val == -1:
break
node = ListNode(val)
cur.next = node
cur = cur.next
return head.next
```
你可以使用这个函数来创建一个链表,例如输入1 2 3 -1,将返回一个包含1、2、3三个节点的链表。
相关问题
c 语言输入链表数据(以数字-1作为输入结束的标志),例如建立链表1 2 3 则需输入1 2 3 -1;
可以使用如下代码实现:
```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;
}
```
C语言用链表建立并输出一组数,输入若干个非负数并以-1作为结束标志
好的,这是一个比较基础的链表操作问题。我们可以按照以下步骤实现:
1. 定义链表节点结构体
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
```
2. 定义链表的头节点
```c
Node* head = NULL;
```
3. 循环读入输入的数并建立链表
```c
int num;
while (1) {
scanf("%d", &num);
if (num == -1) break; // 输入-1,结束输入
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) { // 第一个节点
head = newNode;
} else { // 非第一个节点
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
}
```
4. 输出链表中的数
```c
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
int main() {
Node* head = NULL;
int num;
while (1) {
scanf("%d", &num);
if (num == -1) break; // 输入-1,结束输入
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->next = NULL;
if (head == NULL) { // 第一个节点
head = newNode;
} else { // 非第一个节点
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
}
Node* p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
return 0;
}
```