Skip to content

Commit

Permalink
[LinkedList] optimize Solution for Reorder List
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Jun 16, 2016
1 parent 72e4cd7 commit c6c635d
Showing 1 changed file with 34 additions and 29 deletions.
63 changes: 34 additions & 29 deletions LinkedList/ReorderList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,52 +16,57 @@

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

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


var prev: ListNode? = head
var post: ListNode? = head

_split(&prev, &post)
prev = head

post = _reverse(&post)

_merge(&prev, &post)
}

private func _split(inout prev: ListNode?, inout _ post: ListNode?) {
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?{

private func _reverse(inout 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
}

private func _merge(inout prev: ListNode?, inout _ post: ListNode?) {
while prev != nil && post != nil{
let preNext = prev!.next
let posNext = post!.next

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

prev = preNext
post = posNext
}
}
}

0 comments on commit c6c635d

Please sign in to comment.