链表反转

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
class ListNode:
def __init__(self,x):
self.val = x
self.next = None

def reverse(head):
if head == None or head.next == None:
return head
pre = None
cur = head
h = head
while cur:
h = cur
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return h

head = None
tmp = head
for i in xrange(1,10):
if head == None:
head = ListNode(i)
tmp = head
else:
tmp.next = ListNode(i)
tmp = tmp.next
tmp = head
while tmp:
print tmp.val
tmp = tmp.next

head = reverse(head)
print '----------'
tmp = head
while tmp:
print tmp.val
tmp = tmp.next