Skip to content
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
6 changes: 6 additions & 0 deletions src/data-structures/linked-list/LinkedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ export default class LinkedList {
if (currentNode) {
newNode.next = currentNode.next;
currentNode.next = newNode;

// If the new node was linked after the current tail, it is the new tail.
// Otherwise the next append() would overwrite it and drop the node.
if (currentNode === this.tail) {
this.tail = newNode;
}
} else {
if (this.tail) {
this.tail.next = newNode;
Expand Down
16 changes: 16 additions & 0 deletions src/data-structures/linked-list/__test__/LinkedList.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ describe('LinkedList', () => {
expect(linkedList.toString()).toBe('1,4,2,3,10');
});

it('should update the tail when inserting after the last node', () => {
const linkedList = new LinkedList();

linkedList.append(1).append(2);
linkedList.insert(3, 2);

expect(linkedList.tail.value).toBe(3);
expect(linkedList.toString()).toBe('1,2,3');

linkedList.append(4);

expect(linkedList.toString()).toBe('1,2,3,4');
expect(linkedList.deleteTail().value).toBe(4);
expect(linkedList.deleteTail().value).toBe(3);
});

it('should delete node by value from linked list', () => {
const linkedList = new LinkedList();

Expand Down