-
Notifications
You must be signed in to change notification settings - Fork 178
/
13_ReverseList.py
53 lines (42 loc) · 1.11 KB
/
13_ReverseList.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 反转链表
# 输入一个链表,反转链表后,输出新链表的表头。
# 链表结构
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 打印链表
def printChain(head):
node = head
while node:
print(node.val)
node = node.next
class Solution:
def ReverseList(self, pHead):
if pHead == None:
return None
if pHead.next == None:
return pHead
leftPointer = pHead
middlePointer = pHead.next
rightPointer = pHead.next.next
leftPointer.next = None
while rightPointer != None:
middlePointer.next = leftPointer
leftPointer = middlePointer
middlePointer = rightPointer
rightPointer = rightPointer.next
middlePointer.next = leftPointer
return middlePointer
if __name__ == '__main__':
# 创建链表
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
print(Solution().ReverseList(l1))