-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00141-linked_list_cycle.go
68 lines (53 loc) · 1.2 KB
/
00141-linked_list_cycle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 141: Linked List Cycle
// https://leetcode.com/problems/linked-list-cycle/
package main
import "fmt"
type ListNode struct {
val int
next *ListNode
}
type LinkedList struct {
head *ListNode
}
func llInput(head **ListNode, inputs []int) {
for i:=len(inputs)-1; i>=0; i-- {
node := &ListNode{inputs[i], *head}
*head = node
}
}
func llOutput(head *ListNode) {
for head != nil {
fmt.Print(head.val, " -> ")
head = head.next
}
fmt.Println("NULL")
}
func createLoop(head **ListNode, p int) {
if (*head).next==nil {return}
if p==-1 {return}
tail, node := *head, *head
for tail.next!=nil {tail = tail.next}
for i:=0; i<p; i++ {node = node.next}
tail.next = node
}
// SOLUTION
func hasCycle(head *ListNode) bool {
if (head==nil) {return false}
slow, fast := head, head
for (fast.next!=nil && fast.next.next!=nil) {
slow = slow.next
fast = fast.next.next
if (slow == fast) {return true}
}
return false
}
func main() {
ll := LinkedList{}
// INPUT
li := []int{3,2,0,-4}
llInput(&ll.head, li)
createLoop(&ll.head, 1)
// OUTPUT
result := hasCycle(ll.head)
fmt.Println(result)
}