File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ public class ListNode {
2+ public var val : Int
3+ public var next : ListNode ?
4+ public init ( ) { self . val = 0 ; self . next = nil ; }
5+ public init ( _ val: Int ) { self . val = val; self . next = nil ; }
6+ public init ( _ val: Int , _ next: ListNode ? ) { self . val = val; self . next = next; }
7+ }
8+
9+ class Solution {
10+ // Time O(n)
11+ // Space O(1)
12+ func removeNthFromEnd( _ head: ListNode ? , _ n: Int ) -> ListNode ? {
13+ var slow : ListNode ? = head
14+ var fast : ListNode ? = head
15+ var prev : ListNode ?
16+
17+ for _ in 1 ... n {
18+ fast = fast? . next
19+ }
20+
21+ while fast != nil {
22+ prev = slow
23+ slow = slow? . next
24+ fast = fast? . next
25+ }
26+
27+ if prev != nil {
28+ prev? . next = slow? . next
29+ } else {
30+ return head? . next
31+ }
32+
33+ return head
34+ }
35+ }
36+
You can’t perform that action at this time.
0 commit comments