Skip to content
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

set tail as newNode if currentNode is the tail #1020

Closed
wants to merge 4 commits into from
Closed
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
3 changes: 3 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,9 @@ export default class LinkedList {
if (currentNode) {
newNode.next = currentNode.next;
currentNode.next = newNode;
if (this.tail === currentNode) {
this.tail = newNode;
}
} else {
if (this.tail) {
this.tail.next = newNode;
Expand Down
12 changes: 12 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,18 @@ describe('LinkedList', () => {
expect(linkedList.toString()).toBe('1,4,2,3,10');
});

it('should insert and maintain head and tail', () => {
const linkedList = new LinkedList();

linkedList.insert(2, 0);
linkedList.insert(3, 1);
linkedList.insert(4, 2);

expect(linkedList.toString()).toBe('2,3,4');
expect(linkedList.head.toString()).toBe('2');
expect(linkedList.tail.toString()).toBe('4');
});

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

Expand Down