Skip to content

Commit

Permalink
[LinkedList] Optimize Solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Dec 24, 2016
1 parent 69496a6 commit 864f703
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 21 deletions.
17 changes: 6 additions & 11 deletions LinkedList/PartitionList.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/**
* Question Link: https://leetcode.com/problems/partition-list/
* Primary idea: Tail Insert and merge two lists
*
* Note: Swift provides "!==" to determine two objects refer to the same reference
* Primary idea: Tail Insert and merge two lists, use dummy to avoid edge case
*
* Time Complexity: O(n), Space Complexity: O(1)
* Definition for singly-linked list.
Expand All @@ -17,23 +15,20 @@
*/

class PartitionList {
func partition(head: ListNode?, _ x: Int) -> ListNode? {
let prevDummy = ListNode(0)
var prev = prevDummy
let postDummy = ListNode(0)
var post = postDummy
func partition(_ head: ListNode?, _ x: Int) -> ListNode? {
let prevDummy = ListNode(0), postDummy = ListNode(0)
var prev = prevDummy, post = postDummy

var node = head

while node != nil {
if node!.val < x {
prev.next = node
prev = node!
prev = prev.next!
} else {
post.next = node
post = node!
post = post.next!
}

node = node!.next
}

Expand Down
12 changes: 2 additions & 10 deletions LinkedList/RemoveNthFromEnd.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,19 @@
*/

class RemoveNthFromEnd {
func removeNthFromEnd(head: ListNode?, _ n: Int) -> ListNode? {
guard let head = head else {
return nil
}

func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var prev: ListNode? = dummy
var post: ListNode? = dummy

// move post
for _ in 0 ..< n {
if post == nil {
break
}

post = post!.next
}

// move prev and post at the same time
while post != nil && post!.next != nil {
while post!.next != nil {
prev = prev!.next
post = post!.next
}
Expand Down

0 comments on commit 864f703

Please sign in to comment.