mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Fix the prepend method for the LinkedList (#47)
* Fix LinkedList * Fix the prepend method for the LinkedList
This commit is contained in:
parent
91d4714d19
commit
beb8501aca
@ -21,7 +21,13 @@ export default class LinkedList {
|
||||
*/
|
||||
prepend(value) {
|
||||
// Make new node to be a head.
|
||||
this.head = new LinkedListNode(value, this.head);
|
||||
const newNode = new LinkedListNode(value, this.head);
|
||||
this.head = newNode;
|
||||
|
||||
// If there is no tail yet let's make new node a tail.
|
||||
if (!this.tail) {
|
||||
this.tail = newNode;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
@ -21,10 +21,14 @@ describe('LinkedList', () => {
|
||||
it('should prepend node to linked list', () => {
|
||||
const linkedList = new LinkedList();
|
||||
|
||||
linkedList.append(1);
|
||||
linkedList.prepend(2);
|
||||
expect(linkedList.head.toString()).toBe('2');
|
||||
expect(linkedList.tail.toString()).toBe('2');
|
||||
|
||||
expect(linkedList.toString()).toBe('2,1');
|
||||
linkedList.append(1);
|
||||
linkedList.prepend(3);
|
||||
|
||||
expect(linkedList.toString()).toBe('3,2,1');
|
||||
});
|
||||
|
||||
it('should delete node by value from linked list', () => {
|
||||
|
Loading…
Reference in New Issue
Block a user