Python 输入若干个不超过100的整数,建立单链表,然后将链表中所有结点的链接方向逆置,要求仍利用原表的存储空间。输出逆置后的单链表。
时间: 2024-05-05 15:16:54 浏览: 87
以下是一个可能的实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def reverse_linked_list(head):
if head is None or head.next is None:
return head
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
# 输入若干个不超过100的整数,建立单链表
numbers = list(map(int, input().split()))
head = Node(numbers[0])
curr = head
for num in numbers[1:]:
new_node = Node(num)
curr.next = new_node
curr = new_node
# 将链表中所有结点的链接方向逆置
head = reverse_linked_list(head)
# 输出逆置后的单链表
curr = head
while curr:
print(curr.data, end=" ")
curr = curr.next
```
示例输入:
```
1 2 3 4 5
```
示例输出:
```
5 4 3 2 1
```
阅读全文