链表-中等:分割链表 By Swift

221 阅读1分钟

、* 题目

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
  • 思路 双指针法 + 前哨节点。一个指针指向所有小于 x 的节点,一个指针指向剩余的节点。

  • 代码

class Solution {
    func partition(_ head: ListNode?, _ x: Int) -> ListNode? {
        let dummyBefore = ListNode(0)
        var tempBefore: ListNode? = dummyBefore
        
        
        let dummyAfter = ListNode(0)
        var tempAfter: ListNode? = dummyAfter
        
        var cur = head
        while cur != nil {
            if cur!.val < x {
                tempBefore?.next = cur
                tempBefore = tempBefore?.next
            } else {
                tempAfter?.next = cur
                tempAfter = tempAfter?.next
            }
            
            cur = cur?.next
        }
        
        tempBefore?.next = dummyAfter.next
        tempAfter?.next = nil
        return dummyBefore.next
    }
}