Skip to content

Fix LinkedList.insert not updating the tail when inserting after the last node - #2220

Open
Darkslayer3324j wants to merge 1 commit into
trekhleb:masterfrom
Darkslayer3324j:fix/linked-list-insert-tail
Open

Darkslayer3324j wants to merge 1 commit into
trekhleb:masterfrom
Darkslayer3324j:fix/linked-list-insert-tail

Conversation

@Darkslayer3324j

Copy link
Copy Markdown

LinkedList.insert(value, index) corrupts the list when the value is inserted right after the last node (index === length): the new node is linked after the old tail, but this.tail is not updated. The next append() then writes to the old tail's next, overwriting the inserted node:

const list = new LinkedList();
list.append(1).append(2);
list.insert(3, 2);
list.tail.value;   // 2, should be 3
list.append(4);
list.toString();   // '1,2,4', should be '1,2,3,4'   (3 is lost)

insert already handles an index beyond the end by appending and updating tail (the else branch), and index === 0 via prepend; only this in-between case (walking to the last node and linking after it) missed the tail update. The fix sets this.tail = newNode when the node was linked after the current tail.

Added a test for insert-then-append/deleteTail; it fails on master (1 failed) and passes with the change (21 passed). eslint runs clean via the pre-commit hook.

Found by differential fuzzing (random operation sequences on the data structures compared against a plain-array model); the rest of that pass (heaps, priority queue, hash table, Fenwick tree, disjoint set, LRU caches) matched the model.

Written with AI assistance (Claude Code); I reproduced the bug, traced the cause, and ran the tests and linter.

…last node

insert(value, index) with index equal to the list length linked the new node
after the current tail but left this.tail pointing at the old last node, so a
following append() overwrote the inserted node and it was lost. Update the
tail in that case and add a test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant