输入若干个正整数(输入-1为结束标志),要求按输入数据的逆序建立一个链表,并输出。 输入输出示例: 1 2 3 4 5 6 7 -1 7 6 5 4 3 2 1
时间: 2024-02-05 10:11:05 浏览: 66
链表的正序和逆序输出
以下是 Python 代码实现:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
head = None
while True:
num = int(input())
if num == -1:
break
new_node = ListNode(num)
new_node.next = head
head = new_node
# 遍历链表并输出
while head:
print(head.val, end=' ')
head = head.next
```
输入样例:
```
1
2
3
4
5
6
7
-1
```
输出样例:
```
7 6 5 4 3 2 1
```
阅读全文