Swift solution - Two Pointers


  • 0
    class Solution {
        func partition(_ head: ListNode?, _ x: Int) -> ListNode? {
            let dummy1 = ListNode(0)
            let dummy2 = ListNode(0)
            var cur1: ListNode? = dummy1
            var cur2: ListNode? = dummy2
            var head = head
            
            while head != nil {
                if head!.val < x {
                    cur1?.next = head
                    cur1 = head
                } else {
                    cur2?.next = head
                    cur2 = head
                }
                head = head?.next
            }
            cur2?.next = nil
            cur1?.next = dummy2.next
            
            return dummy1.next
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.