Skip to content

Add cycle creation utility and detection tests for Linked List (Fixes #583) #2052

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/algorithms/linked-list/cycle/__tests__/cycle.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import LinkedList from '../../../../data-structures/linked-list/LinkedList';
import createCycle from '../createCycle';
import detectCycle from '../detectCycle';

describe('Linked List Cycle Tests', () => {
let list;

beforeEach(() => {
list = new LinkedList();
});

test('detectCycle returns false on list with no cycle', () => {
list
.append(1)
.append(9)
.append(87)
.append(5)
.append(22);
expect(detectCycle(list)).toBe(false);
});

test('createCycle creates a cycle and detectCycle detects it', () => {
list
.append(1)
.append(9)
.append(87)
.append(5)
.append(22);
createCycle(list, 2); // Creates cycle linking tail to node at index 2 (value 87)
expect(detectCycle(list)).toBe(true);
});

test('createCycle with invalid position does not create cycle', () => {
list
.append(1)
.append(9)
.append(87);
createCycle(list, 10); // Invalid index, no cycle should be created
expect(detectCycle(list)).toBe(false);
});

test('createCycle with position -1 does not create cycle', () => {
list
.append(1)
.append(9)
.append(87);
createCycle(list, -1); // No cycle created
expect(detectCycle(list)).toBe(false);
});
});
24 changes: 24 additions & 0 deletions src/algorithms/linked-list/cycle/createCycle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export default function createCycle(linkedList, position) {
if (!linkedList.head || position < 0) return;

let cycleNode = null;
let tail = linkedList.head;
let index = 0;

while (tail.next) {
if (index === position) {
cycleNode = tail;
}
tail = tail.next;
index += 1;
}

// For the last node
if (index === position) {
cycleNode = tail;
}

if (cycleNode) {
tail.next = cycleNode;
}
}
15 changes: 15 additions & 0 deletions src/algorithms/linked-list/cycle/detectCycle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export default function detectCycle(linkedList) {
let slow = linkedList.head;
let fast = linkedList.head;

while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;

if (slow === fast) {
return true;
}
}

return false;
}