-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path链表逆转输出.py
45 lines (40 loc) · 1.16 KB
/
链表逆转输出.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
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
lastNode = ListNode(0)
def TravelSel(self, pHead):
#递归遍历链表,将后一个节点的next指向前一个,第一个节点没有处理
if pHead.next:
self.TravelSel(pHead.next)
pHead.next.next = pHead
#返回头节点
return pHead
else:
self.lastNode = pHead
#返回头节点
return pHead
def ReverseList(self, pHead):
if not pHead:
return None
first = self.TravelSel(pHead)
#将头结点的next指针指向None
first.next = None
return self.lastNode
if __name__ == "__main__":
the_listnode = ListNode(0)
tmp = the_listnode
for i in range(1, 11):
tmp.next = ListNode(i)
tmp = tmp.next
the_listnode = the_listnode.next
a = Solution()
b = a.ReverseList(the_listnode)
for i in range(15):
try:
print b.val
b = b.next
except AttributeError,e:
print u"后面木有了"