美文网首页
35.翻转链表(Python)

35.翻转链表(Python)

作者: 八菜冰 | 来源:发表于2018-12-15 23:40 被阅读0次
    • 描述
      给定一个链表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
    
    

    相关文章

      网友评论

          本文标题:35.翻转链表(Python)

          本文链接:https://www.haomeiwen.com/subject/sybzhqtx.html