File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed
lcof2/剑指 Offer II 021. 删除链表的倒数第 n 个结点 Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -238,6 +238,41 @@ def remove_nth_from_end(head, n)
238
238
end
239
239
```
240
240
241
+ #### Swift
242
+
243
+ ``` swift
244
+ /* class ListNode {
245
+ * var val: Int
246
+ * var next: ListNode?
247
+ * init() { self.val = 0; self.next = nil }
248
+ * init(_ val: Int) { self.val = val; self.next = nil }
249
+ * init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next }
250
+ * }
251
+ */
252
+
253
+ class Solution {
254
+ func removeNthFromEnd (_ head : ListNode? , _ n : Int ) -> ListNode? {
255
+ let dummy = ListNode (0 , head)
256
+ var fast: ListNode? = dummy
257
+ var slow: ListNode? = dummy
258
+
259
+ var n = n
260
+ while n > 0 {
261
+ fast = fast? .next
262
+ n -= 1
263
+ }
264
+
265
+ while fast? .next != nil {
266
+ slow = slow? .next
267
+ fast = fast? .next
268
+ }
269
+
270
+ slow? .next = slow? .next ? .next
271
+ return dummy.next
272
+ }
273
+ }
274
+ ```
275
+
241
276
<!-- tabs: end -->
242
277
243
278
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ /* class ListNode {
2
+ * var val: Int
3
+ * var next: ListNode?
4
+ * init() { self.val = 0; self.next = nil }
5
+ * init(_ val: Int) { self.val = val; self.next = nil }
6
+ * init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next }
7
+ * }
8
+ */
9
+
10
+ class Solution {
11
+ func removeNthFromEnd( _ head: ListNode ? , _ n: Int ) -> ListNode ? {
12
+ let dummy = ListNode ( 0 , head)
13
+ var fast : ListNode ? = dummy
14
+ var slow : ListNode ? = dummy
15
+
16
+ var n = n
17
+ while n > 0 {
18
+ fast = fast? . next
19
+ n -= 1
20
+ }
21
+
22
+ while fast? . next != nil {
23
+ slow = slow? . next
24
+ fast = fast? . next
25
+ }
26
+
27
+ slow? . next = slow? . next? . next
28
+ return dummy. next
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments