python 实现链表的反转

从头开始遍历,每一个节点的next指向它的前一个节点。

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

def nonrecurse(head):
if head is None or head.next is 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 = ListNode(1)
p1=ListNode(2)
p2=ListNode(3)
p3=ListNode(4)
head.next = p1
p1.next = p2
p2.next = p3
p=nonrecurse(head)
while p:
print p.val
p=p.next



head = ListNode(1)
p1=ListNode(2)
p2=ListNode(3)
p3=ListNode(4)
head.next = p1
p1.next = p2
p2.next = p3
p=nonrecurse(head)
while p:
print p.val
p=p.next