zoukankan      html  css  js  c++  java
  • LeetCode 206.反转链表

    反转一个单链表。

    #
    # @lc app=leetcode.cn id=206 lang=python3
    #
    # [206] 反转链表
    #
    
    # @lc code=start
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    # 优先使用迭代法1,因为迭代法1在整个过程中没有拆断链表
    # 迭代法1
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            """
            input:1,2,3,4,5
            pre,1(cur),2(tmp),3,4,5
            pre,2,1(cur),3,4,5
            pre,3,2,1(cur),4,5
            pre,4,3,2,1(cur),5
            pre,5,4,3,2,1(cur)  当cur.next is None时,终止循环
            """
            if head is None or head.next is None:
                return head
            pre = ListNode(None)
            pre.next = head
            cur = head
            while cur.next:
                tmp = cur.next
                cur.next = tmp.next         
                tmp.next = pre.next
                pre.next = tmp
            return pre.next 
    
    # 迭代法2
    # input:1,2,3,4,5
    # Process :
    # new_head = None       cur = 1,2,3,4,5
    # new_head = 1          cur = 2,3,4,5
    # new_head = 2,1        cur = 3,4,5
    # new_head = 3,2,1      cur = 4,5
    # new_head = 4,3,2,1    cur = 5
    # new_head = 5,4,3,2,1  cur = None
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            cur = head
            new_head = None
            while cur:
                tmp = cur.next
                cur.next = new_head
                new_head = cur
                cur = tmp
            return new_head
    # 递归法
    """
    子问题是什么
    base case是什么
    在当前层要干什么
    对翻转链表来说,以1->2->3->4->5为例:
    子问题是:除去current node,翻转剩余链表,即除去1, reverseList(2->3->4->5),递归得到的解是 5->4->3->2
    base case:当前节点为空,返回空,当前节点的next为空(只剩余一个节点),返回该节点
    在当前层要干什么:翻转链表,即把1->2变为2->1.
    最后return的是结果链表的头,也就是递归解的头。
    """
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            """
            递归三要素:
                  返回条件: 头节点为空或头节点next节点为空
                  子问题:对head.next子链表进行反转
                  当前层的处理:head.next子链表反转后的头节点是node,尾节点是head.next,需要将head节点链在head.next尾部,并将head.next置空
            """
            if head is None or head.next is None:
                return head
            node = self.reverseList(head.next) ## 对子链表进行反转
            head.next.next = head  # head.next 是子链表的尾节点,连接上新的尾节点head
            head.next = None # 新的尾节点置为None
            return node # 返回新的头节点
    
    
  • 相关阅读:
    Java基本语法--程序流程控制
    Java基本语法--控制台输入(Scanner类)
    Java基本语法--运算符
    curl:出现SSL错误提示
    升级ruby的版本
    Linux之expect非交互式功能
    Rsync备份同步数据工具
    Linux发展历史
    解决DDOS攻击生产案例
    用shell脚本监控MySQL主从同步
  • 原文地址:https://www.cnblogs.com/sandy-t/p/12949096.html
Copyright © 2011-2022 走看看