File tree Expand file tree Collapse file tree 3 files changed +99
-0
lines changed
lcci/02.08.Linked List Cycle Expand file tree Collapse file tree 3 files changed +99
-0
lines changed Original file line number Diff line number Diff line change @@ -204,3 +204,37 @@ var detectCycle = function (head) {
204
204
return null ;
205
205
};
206
206
```
207
+
208
+ ``` swift
209
+ /*
210
+ * public class ListNode {
211
+ * var val: Int
212
+ * var next: ListNode?
213
+ * init(_ x: Int) {
214
+ * self.val = x
215
+ * self.next = nil
216
+ * }
217
+ * }
218
+ */
219
+
220
+ class Solution {
221
+ func detectCycle (_ head : ListNode? ) -> ListNode? {
222
+ var slow = head
223
+ var fast = head
224
+
225
+ while fast != nil && fast? .next != nil {
226
+ slow = slow? .next
227
+ fast = fast? .next ? .next
228
+ if slow === fast {
229
+ var ans = head
230
+ while ans !== slow {
231
+ ans = ans? .next
232
+ slow = slow? .next
233
+ }
234
+ return ans
235
+ }
236
+ }
237
+ return nil
238
+ }
239
+ }
240
+ ```
Original file line number Diff line number Diff line change @@ -233,6 +233,40 @@ var detectCycle = function (head) {
233
233
};
234
234
```
235
235
236
+ ``` swift
237
+ /*
238
+ * public class ListNode {
239
+ * var val: Int
240
+ * var next: ListNode?
241
+ * init(_ x: Int) {
242
+ * self.val = x
243
+ * self.next = nil
244
+ * }
245
+ * }
246
+ */
247
+
248
+ class Solution {
249
+ func detectCycle (_ head : ListNode? ) -> ListNode? {
250
+ var slow = head
251
+ var fast = head
252
+
253
+ while fast != nil && fast? .next != nil {
254
+ slow = slow? .next
255
+ fast = fast? .next ? .next
256
+ if slow === fast {
257
+ var ans = head
258
+ while ans !== slow {
259
+ ans = ans? .next
260
+ slow = slow? .next
261
+ }
262
+ return ans
263
+ }
264
+ }
265
+ return nil
266
+ }
267
+ }
268
+ ```
269
+
236
270
<!-- tabs: end -->
237
271
238
272
<!-- end -->
Original file line number Diff line number Diff line change
1
+ /*
2
+ * public class ListNode {
3
+ * var val: Int
4
+ * var next: ListNode?
5
+ * init(_ x: Int) {
6
+ * self.val = x
7
+ * self.next = nil
8
+ * }
9
+ * }
10
+ */
11
+
12
+ class Solution {
13
+ func detectCycle( _ head: ListNode ? ) -> ListNode ? {
14
+ var slow = head
15
+ var fast = head
16
+
17
+ while fast != nil && fast? . next != nil {
18
+ slow = slow? . next
19
+ fast = fast? . next? . next
20
+ if slow === fast {
21
+ var ans = head
22
+ while ans !== slow {
23
+ ans = ans? . next
24
+ slow = slow? . next
25
+ }
26
+ return ans
27
+ }
28
+ }
29
+ return nil
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments