Skip to content

Commit f51ffa7

Browse files
Add linked list cycle detection tests and cycle creation utility
1 parent e40a67b commit f51ffa7

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import LinkedList from '../../../../data-structures/linked-list/LinkedList';
2+
import createCycle from '../createCycle';
3+
import detectCycle from '../detectCycle';
4+
5+
describe('Linked List Cycle Tests', () => {
6+
let list;
7+
8+
beforeEach(() => {
9+
list = new LinkedList();
10+
});
11+
12+
test('detectCycle returns false on list with no cycle', () => {
13+
list
14+
.append(1)
15+
.append(9)
16+
.append(87)
17+
.append(5)
18+
.append(22);
19+
expect(detectCycle(list)).toBe(false);
20+
});
21+
22+
test('createCycle creates a cycle and detectCycle detects it', () => {
23+
list
24+
.append(1)
25+
.append(9)
26+
.append(87)
27+
.append(5)
28+
.append(22);
29+
createCycle(list, 2); // Creates cycle linking tail to node at index 2 (value 87)
30+
expect(detectCycle(list)).toBe(true);
31+
});
32+
33+
test('createCycle with invalid position does not create cycle', () => {
34+
list
35+
.append(1)
36+
.append(9)
37+
.append(87);
38+
createCycle(list, 10); // Invalid index, no cycle should be created
39+
expect(detectCycle(list)).toBe(false);
40+
});
41+
42+
test('createCycle with position -1 does not create cycle', () => {
43+
list
44+
.append(1)
45+
.append(9)
46+
.append(87);
47+
createCycle(list, -1); // No cycle created
48+
expect(detectCycle(list)).toBe(false);
49+
});
50+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
export default function createCycle(linkedList, position) {
2+
if (!linkedList.head || position < 0) return;
3+
4+
let cycleNode = null;
5+
let tail = linkedList.head;
6+
let index = 0;
7+
8+
while (tail.next) {
9+
if (index === position) {
10+
cycleNode = tail;
11+
}
12+
tail = tail.next;
13+
index += 1;
14+
}
15+
16+
// For the last node
17+
if (index === position) {
18+
cycleNode = tail;
19+
}
20+
21+
if (cycleNode) {
22+
tail.next = cycleNode;
23+
}
24+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export default function detectCycle(linkedList) {
2+
let slow = linkedList.head;
3+
let fast = linkedList.head;
4+
5+
while (fast && fast.next) {
6+
slow = slow.next;
7+
fast = fast.next.next;
8+
9+
if (slow === fast) {
10+
return true;
11+
}
12+
}
13+
14+
return false;
15+
}

0 commit comments

Comments
 (0)