diff --git a/lcci/02.08.Linked List Cycle/README.md b/lcci/02.08.Linked List Cycle/README.md index f4d7812b41b06..4bdacbd682de3 100644 --- a/lcci/02.08.Linked List Cycle/README.md +++ b/lcci/02.08.Linked List Cycle/README.md @@ -204,3 +204,37 @@ var detectCycle = function (head) { return null; }; ``` + +```swift +/* +* public class ListNode { +* var val: Int +* var next: ListNode? +* init(_ x: Int) { +* self.val = x +* self.next = nil +* } +* } +*/ + +class Solution { + func detectCycle(_ head: ListNode?) -> ListNode? { + var slow = head + var fast = head + + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + if slow === fast { + var ans = head + while ans !== slow { + ans = ans?.next + slow = slow?.next + } + return ans + } + } + return nil + } +} +``` diff --git a/lcci/02.08.Linked List Cycle/README_EN.md b/lcci/02.08.Linked List Cycle/README_EN.md index eb7816651a316..c3e291519ca6b 100644 --- a/lcci/02.08.Linked List Cycle/README_EN.md +++ b/lcci/02.08.Linked List Cycle/README_EN.md @@ -233,6 +233,40 @@ var detectCycle = function (head) { }; ``` +```swift +/* +* public class ListNode { +* var val: Int +* var next: ListNode? +* init(_ x: Int) { +* self.val = x +* self.next = nil +* } +* } +*/ + +class Solution { + func detectCycle(_ head: ListNode?) -> ListNode? { + var slow = head + var fast = head + + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + if slow === fast { + var ans = head + while ans !== slow { + ans = ans?.next + slow = slow?.next + } + return ans + } + } + return nil + } +} +``` + diff --git a/lcci/02.08.Linked List Cycle/Solution.swift b/lcci/02.08.Linked List Cycle/Solution.swift new file mode 100644 index 0000000000000..fbed4eae0d4c9 --- /dev/null +++ b/lcci/02.08.Linked List Cycle/Solution.swift @@ -0,0 +1,31 @@ +/* +* public class ListNode { +* var val: Int +* var next: ListNode? +* init(_ x: Int) { +* self.val = x +* self.next = nil +* } +* } +*/ + +class Solution { + func detectCycle(_ head: ListNode?) -> ListNode? { + var slow = head + var fast = head + + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + if slow === fast { + var ans = head + while ans !== slow { + ans = ans?.next + slow = slow?.next + } + return ans + } + } + return nil + } +}