Skip to content

Commit ae26fb8

Browse files
committed
solve
1 parent 59d8483 commit ae26fb8

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* public var val: Int
5+
* public var next: ListNode?
6+
* public init() { self.val = 0; self.next = nil; }
7+
* public init(_ val: Int) { self.val = val; self.next = nil; }
8+
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
9+
* }
10+
*/
11+
class Solution {
12+
// O(n) time / O(n) space
13+
func removeNthFromEndList(_ head: ListNode?, _ n: Int) -> ListNode? {
14+
var nodes = [ListNode]()
15+
var node = head
16+
while let current = node {
17+
nodes.append(current)
18+
node = current.next
19+
}
20+
21+
let indexToRemove = nodes.count - n
22+
23+
if indexToRemove == 0 {
24+
return head?.next
25+
}
26+
27+
nodes[indexToRemove - 1].next = indexToRemove + 1 < nodes.count ? nodes[indexToRemove + 1] : nil
28+
return head
29+
}
30+
31+
// O(n) time / O(1) space
32+
func removeNthFromEndPointer(_ head: ListNode?, _ n: Int) -> ListNode? {
33+
let dummy = ListNode(0)
34+
dummy.next = head
35+
var post: ListNode? = dummy
36+
var prev: ListNode? = dummy
37+
38+
for _ in 0...n {
39+
post = post?.next
40+
}
41+
42+
while post != nil {
43+
prev = prev?.next
44+
post = post?.next
45+
}
46+
47+
prev?.next = prev?.next?.next
48+
return dummy.next
49+
}
50+
}

0 commit comments

Comments
 (0)