Swift solution


  • 0
    class Solution {
        func reorderList(_ head: ListNode?) {
            if head == nil || head?.next == nil {
                return
            }
            
            var p1: ListNode? = head
            var p2: ListNode? = head
            while p2?.next != nil && p2?.next?.next != nil {
                p1 = p1?.next
                p2 = p2?.next?.next
            }
            
            let preMiddle: ListNode? = p1
            let preCur: ListNode? = p1?.next
            while preCur?.next != nil {
                let cur = preCur?.next
                preCur?.next = cur?.next
                cur?.next = preMiddle?.next
                preMiddle?.next = cur
            }
            
            p1 = head
            p2 = preMiddle?.next
            while p1 !== preMiddle {
                preMiddle?.next = p2?.next
                p2?.next = p1?.next
                p1?.next = p2
                p1 = p2?.next
                p2 = preMiddle?.next
            }
        }
    }
    

Log in to reply
 

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