Skip to content

Commit 1422ade

Browse files
committed
solve problem
1 parent ad88b16 commit 1422ade

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+

0 commit comments

Comments
 (0)