Skip to content

Commit

Permalink
[LinkedList] add Solution to Reorder List
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed May 14, 2016
1 parent db6948f commit 740eb61
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions LinkedList/ReorderList.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Question Link: https://leetcode.com/problems/reorder-list/
* Primary idea: Use Runner Tech to split the list, reverse the second half, and merge them
* Time Complexity: O(n), Space Complexity: O(1)
*
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/

class ReorderList {
func reorderList(head: ListNode?) {
if head == nil || head!.next == nil {
return
}

// split the list
var prev = head
var post = head!.next

while post != nil && post!.next != nil {
prev = prev!.next
post = post!.next!.next
}

post = prev!.next
prev!.next = nil
prev = head

// reverse the second list
post = _reverse(post)

// merge lists
while prev != nil && post != nil{
let preNext = prev!.next
let posNext = post!.next

prev!.next = post
post!.next = preNext

prev = preNext
post = posNext
}
}

private func _reverse(head: ListNode?) -> ListNode?{
var prev = head
var temp: ListNode?

while prev != nil {
let post = prev!.next

prev!.next = temp

temp = prev
prev = post
}

return temp
}
}

0 comments on commit 740eb61

Please sign in to comment.