反转单向链表

输入一个链表,输出反转后的链表。

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class :
def __init__(self,data):
self.data=data
self.next=None
def reverse(phead):
if phead is None or phead.next==None:
return phead
last=None
while phead:
# temp存储当前节点的下一个节点,防止当前节点的next变化而丢失原来指向的节点
temp=phead.next
phead.next=last
# last和当前节点均向后移,重复执行上面的操作
last=phead
phead=temp
return last