- 描述
给定一个链表1->2->3->null,这个翻转后的链表为3->2->1->null。 - Solution
思路:用cur记录p的下一个节点,pre记录上一个节点,p为head,先保存cur,再将p的下一个节点赋值为上一个节点pre,即pre <- p (->) cur ,更新pre为p,p更新为下一个节点cur。再循环,出现 pre p -> cur,再将p - > pre,p = cur。重复..
class Solution:
"""
@param head: n
@return: The new head of reversed linked list.
"""
def reverse(self, head):
# write your code here
if head is None:
return None
p = head
cur = None
pre = None
while p is not None:
cur = p.next
p.next = pre
pre = p
p = cur
return pre
网友评论