-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list_cycle_test.dart
51 lines (42 loc) · 1.12 KB
/
linked_list_cycle_test.dart
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
import 'package:test/test.dart';
bool hasCycle(Node head) {
Node? slow = head, fast = head;
while (true) {
slow = slow!.next;
fast = fast!.next?.next;
if (fast == null) return false;
if (fast == slow) return true;
}
}
class Node {
Node(this.value, [this.next]);
int value;
Node? next;
}
void main() {
group('hasCycle', () {
test('my examples', () {
expect(hasCycle(Node(4)), false);
expect(hasCycle(Node(3, Node(2, Node(1)))), false);
expect(hasCycle(Node(3, Node(2, Node(1, Node(0))))), false);
late Node n;
late Node cyclic;
n = Node(0);
cyclic = Node(3, Node(2, Node(1, n)));
n.next = cyclic;
expect(hasCycle(cyclic), true);
n = Node(0);
cyclic = Node(3, Node(2, Node(1, n)));
n.next = cyclic.next;
expect(hasCycle(cyclic), true);
n = Node(0);
cyclic = Node(3, Node(2, Node(1, n)));
n.next = cyclic.next!.next;
expect(hasCycle(cyclic), true);
n = Node(0);
cyclic = Node(3, Node(2, Node(1, n)));
n.next = cyclic.next!.next!.next;
expect(hasCycle(cyclic), true);
});
});
}