Skip to content

Commit

Permalink
[LinkedList] add solution to Remove Nth Node From End of List
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed May 12, 2016
1 parent 19a2fc6 commit 2efc072
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions LinkedList/RemoveNthFromEnd.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Question Link: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
* Primary idea: Runner Tech
* 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 RemoveNthFromEnd {
func removeNthFromEnd(head: ListNode?, _ n: Int) -> ListNode? {
guard let head = head else {
return nil
}

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 {
prev = prev!.next
post = post!.next
}

prev!.next = prev!.next!.next

return dummy.next
}
}

0 comments on commit 2efc072

Please sign in to comment.