1. 程式人生 > 其它 >【maven多模組工程打包部署】

【maven多模組工程打包部署】

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