链表从链表尾到链表头逆序输出
时间: 2024-01-04 08:18:09 浏览: 81
以下是两种Python实现链表逆序输出的方法:
1. 借助一个新的空链表
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
new_head = None
while head:
temp = head.next
head.next = new_head
new_head = head
head = temp
return new_head
# 测试
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
s = Solution()
new_head = s.reverseList(node1)
while new_head:
print(new_head.val)
new_head = new_head.next
```
2. 在原链表上直接逆序
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
last = None
while head:
temp = head.next
head.next = last
last = head
head = temp
return last
# 测试
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
s = Solution()
new_head = s.reverseList(node1)
while new_head:
print(new_head.val)
new_head = new_head.next
```
阅读全文