将链表逆置,即最后一个结点变成第一个结点,原来倒数第二个结点变成第二个结点,如此等等。数据结构自定义输入
时间: 2023-06-01 07:03:37 浏览: 94
链表的定义如下:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
```
输入样例:
```
1 2 3 4 5
```
输出样例:
```
5 4 3 2 1
```
代码如下:
```python
def reverse_linked_list(head):
if head is None or head.next is None:
return head
pre_node = None
while head:
next_node = head.next
head.next = pre_node
pre_node = head
head = next_node
return pre_node
def print_linked_list(head):
while head:
print(head.value, end=' ')
head = head.next
print()
if __name__ == '__main__':
values = input().split()
head = Node(int(values[0]))
node = head
for value in values[1:]:
node.next = Node(int(value))
node = node.next
new_head = reverse_linked_list(head)
print_linked_list(new_head)
```
阅读全文
相关推荐
















