zoukankan      html  css  js  c++  java
  • LeetCode 143. 重排链表

    143. 重排链表

    Difficulty: 中等

    给定一个单链表 LL0→_L_1→…→_L_n-1→_L_n ,
    将其重新排列后变为: L0→_L_n→_L_1→_L_n-1→_L_2→_L_n-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.
    

    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
    

    Solution

    这题的难度应该不止中等,挺难的,操作有点复杂。参考题解:Java solution with 3 steps - LeetCode Discuss
    第二步

    第三步

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def reorderList(self, head: ListNode) -> None:
            """
            Do not return anything, modify head in-place instead.
            """
            if not head or not head.next: return 
            p1 = p2 = head
            # find the middle
            while p2.next and p2.next.next:
                p1 = p1.next
                p2 = p2.next.next
    ​
            # reverse the half after middle
            mid = p1
            pCurrent = p1.next
            while pCurrent.next:
                current = pCurrent.next
                pCurrent.next = current.next
                current.next = mid.next
                mid.next = current
     
            p1 = head
            p2 = mid.next
            while p1 != mid:
                mid.next = p2.next
                p2.next = p1.next
                p1.next = p2
                p1 = p2.next
                p2 = mid.next
    
  • 相关阅读:
    Redis_配置文件
    Redis_数据使用
    QQ登录测试用例
    JMeter性能测试入门--偏重工具的使用
    浅说《测试用例》
    axure界面功能
    性能测试相关术语
    测试用例设计和测试环境搭建
    测试需求分析
    软件测试的过程
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14183454.html
Copyright © 2011-2022 走看看