class linkedlist(object):
def __init__(self, x):
self.val=x
self.next=None
def reverse(phead):
if not phead or not phead.next:
return phead
last =None #头节点变尾节点,所以下一个节点是空
while phead:
tmp = phead.next #先保存头节点的下一个节点,因为要断开连接丢失
phead.next=last #将头节点反转方向
last =phead #last 变位当前节点
phead=tmp # 头节点变为当前头节点的下一个节点,重复上述操作
return last
测试
node1 = linkedlist(1)
node2 = linkedlist(2)
node3 = linkedlist(3)
node1.next= node2
node2.next = node3
new = reverse(node1)
new.val
3