File tree Expand file tree Collapse file tree 3 files changed +99
-0
lines changed
lcci/02.02.Kth Node From End of List Expand file tree Collapse file tree 3 files changed +99
-0
lines changed Original file line number Diff line number Diff line change @@ -203,6 +203,40 @@ var kthToLast = function (head, k) {
203
203
};
204
204
```
205
205
206
+ ``` swift
207
+ /**
208
+ * Definition for singly-linked list.
209
+ * public class ListNode {
210
+ * var val: Int
211
+ * var next: ListNode?
212
+ * init(_ x: Int, _ next: ListNode? = nil) {
213
+ * self.val = x
214
+ * self.next = next
215
+ * }
216
+ * }
217
+ */
218
+
219
+ class Solution {
220
+ func kthToLast (_ head : ListNode? , _ k : Int ) -> Int {
221
+ var slow = head
222
+ var fast = head
223
+ var k = k
224
+
225
+ while k > 0 {
226
+ fast = fast? .next
227
+ k -= 1
228
+ }
229
+
230
+ while fast != nil {
231
+ slow = slow? .next
232
+ fast = fast? .next
233
+ }
234
+
235
+ return slow? .val ?? 0
236
+ }
237
+ }
238
+ ```
239
+
206
240
<!-- tabs: end -->
207
241
208
242
<!-- end -->
Original file line number Diff line number Diff line change @@ -205,6 +205,40 @@ var kthToLast = function (head, k) {
205
205
};
206
206
```
207
207
208
+ ``` swift
209
+ /**
210
+ * Definition for singly-linked list.
211
+ * public class ListNode {
212
+ * var val: Int
213
+ * var next: ListNode?
214
+ * init(_ x: Int, _ next: ListNode? = nil) {
215
+ * self.val = x
216
+ * self.next = next
217
+ * }
218
+ * }
219
+ */
220
+
221
+ class Solution {
222
+ func kthToLast (_ head : ListNode? , _ k : Int ) -> Int {
223
+ var slow = head
224
+ var fast = head
225
+ var k = k
226
+
227
+ while k > 0 {
228
+ fast = fast? .next
229
+ k -= 1
230
+ }
231
+
232
+ while fast != nil {
233
+ slow = slow? .next
234
+ fast = fast? .next
235
+ }
236
+
237
+ return slow? .val ?? 0
238
+ }
239
+ }
240
+ ```
241
+
208
242
<!-- tabs: end -->
209
243
210
244
<!-- end -->
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * var val: Int
5
+ * var next: ListNode?
6
+ * init(_ x: Int, _ next: ListNode? = nil) {
7
+ * self.val = x
8
+ * self.next = next
9
+ * }
10
+ * }
11
+ */
12
+
13
+ class Solution {
14
+ func kthToLast( _ head: ListNode ? , _ k: Int ) -> Int {
15
+ var slow = head
16
+ var fast = head
17
+ var k = k
18
+
19
+ while k > 0 {
20
+ fast = fast? . next
21
+ k -= 1
22
+ }
23
+
24
+ while fast != nil {
25
+ slow = slow? . next
26
+ fast = fast? . next
27
+ }
28
+
29
+ return slow? . val ?? 0
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments