feat(datastructures): add SelfOrganizingLinkedList implementation and tests - #7575
feat(datastructures): add SelfOrganizingLinkedList implementation and tests#7575iamcodinghere22 wants to merge 20 commits into
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Hi @DenizAltunkapan @yanglbme @alxkm, |
DenizAltunkapan
left a comment
There was a problem hiding this comment.
Nice addition, a self-organizing list with move-to-front is a good fit here and there's no existing one. The algorithm itself looks correct. A few things to sort out before this can go in, left inline.
| * | ||
| * @param <E> the type of element held in this node | ||
| */ | ||
| class LinkedList<E> { |
There was a problem hiding this comment.
Calling the node class LinkedList is confusing, it's a node, not a list, and it clashes with java.util.LinkedList. The repo already has a convention for this (SinglyLinkedListNode). Could you rename it to Node and make it a static nested class inside SelfOrganizingLinkedList? That also keeps it to one top-level class per file, which is what the other list files do.
|
|
||
| /** Returns true if the list contains no elements. */ | ||
| public boolean isEmpty() { | ||
| return head == null; |
There was a problem hiding this comment.
Codecov flags two uncovered lines, these getters (getSize / isEmpty) look like the culprits. Worth a small test so the patch is fully covered.
| assertTrue(list.search(30)); | ||
|
|
||
| // '30' should now be the new head | ||
| assertEquals(30, list.getHeadValue()); |
There was a problem hiding this comment.
The tests only check getHeadValue, so they confirm the searched element ends up at the front but never that the rest of the list survives. A broken move-to-front (lost node, cycle, wrong order) would still pass all of these. Could you add a test that walks the whole list after a search and asserts the full order plus unchanged size? A duplicate-value case would be good too.
This PR implements the Self-Organizing Linked List data structure using the "Move To Front(MTF)" heuristic.
In this implementation, whenever an element is accessed/searched, it is dynamically moved to the head of the list. This optimizes access time for frequently requested items by keeping them near the front, achieving an {O(1)} best-case lookup time for repeated accesses.
Changes Included
SelfOrganizingLinkedList.javaundercom.thealgorithms.datastructures.lists.SelfOrganizingLinkedListTest.javaverifying search, insertion, edge cases (empty list, non-existent elements), and move-to-front behavior.Testing
SelfOrganizingLinkedListTest.javapass locally (mvn test -Dtest=SelfOrganizingLinkedListTest).Checklist