Skip to content

Commit 8db7e1e

Browse files
authored
Create: 19-Remove-Nth-Node-From-End-of-List.swift
1 parent f0c76fb commit 8db7e1e

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
func removeNthFromEnd(_ head: ListNode?, _ n: Int) -> ListNode? {
13+
if head === nil {
14+
return head
15+
}
16+
var slow = head, fast = head
17+
for i in 1...n + 1 {
18+
if (slow === nil) {
19+
return head?.next
20+
}
21+
slow = slow?.next
22+
}
23+
24+
while slow != nil {
25+
slow = slow?.next
26+
fast = fast?.next
27+
}
28+
fast?.next = fast?.next?.next
29+
return head
30+
}
31+
}

0 commit comments

Comments
 (0)