forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[LinkedList] add Solution to Reorder List
- Loading branch information
Yi Gu
committed
May 14, 2016
1 parent
db6948f
commit 740eb61
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |