-
Notifications
You must be signed in to change notification settings - Fork 894
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 Remove Nth Node From End of List
- Loading branch information
Yi Gu
committed
May 12, 2016
1 parent
19a2fc6
commit 2efc072
Showing
1 changed file
with
47 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,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 | ||
} | ||
} |