I want to print all of my linked List item using Javascript. Here I create Node class for this. But My printlist() method prints undifined. Can any one help me?
Here Is my Code:
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.head = null;
}
setNextNode(node) {
this.next = node;
}
getNextNode() {
return this.next;
}
printlist() {
let newhead = this.head;
let output = " ";
while (newhead !== null) {
output += newhead.data + ' ';
console.log(output);
newhead = newhead.getNextNode(this.next);
}
}
}
const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
n1.next = n2;
n2.next = n3;
//console.log(n1);
console.log(n1.printlist());
in your constructor, you should set a value for this.head (something like this or this.next).
class Node {
constructor(data) {
this.data = data;
this.next = null;
this.head = this;
}
setNextNode(node) {
this.next = node;
}
getNextNode() {
return this.next;
}
printlist() {
let newhead = this.head;
let output = " ";
while (newhead !== null) {
output += newhead.data + ' ';
console.log(output);
newhead = newhead.getNextNode(this.next);
}
}
}
const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
n1.next = n2;
n2.next = n3;
//console.log(n1);
console.log(n1.printlist());
The problem is that your node's head reference is null, so the loop in printList will not loop.
The concept of head is not one that belongs to the Node class, but to a container class. It is a reference to a first node, so it shouldn't be a property of every node.
I would also not have a printList method, but make the list iterable. That way it becomes much more flexible, and printing becomes very easy for the caller.
Here is how to do that:
class Node {
constructor(data, next=null) { // Allow optional argument
this.data = data;
this.next = next;
// No head property here
}
}
class LinkedList {
constructor() {
this.head = null; // Here we want a head reference
}
prepend(data) {
this.head = new Node(data, this.head);
}
*[Symbol.iterator]() { // Make a list iterable
let node = this.head;
while (node) {
yield node.data;
node = node.next;
}
}
}
const list = new LinkedList();
list.prepend(3);
list.prepend(2);
list.prepend(1);
console.log(...list); // This will call the iterator method
Related
me and my partner have an issue. in the addToTail method we end by reassigning veryEndResult to newNode (veryEndResult = newNode).
What we were actually trying to do is reassign the value of veryEndResult (this.head.next) to newNode, is there a way to do this? We couldn't google it either because we don't really know how to go about forming that question.
Would love if an experienced coder could help us out on this.
class LinkedList {
constructor () {
this.head = null;
this.length = 0;
}
addToHead (data) {
const newNode = new LinkedListNode(data, this.head);
this.head = newNode;
this.length ++;
return true;
}
addToTail (data) {
const newNode = new LinkedListNode(data, null);
let test = ['this','head'];
this.length ++;
for (let i = 0 ; i < this.length - 1 ; i++) {
test.push('next');
}
let endResult = test.join('.');
let veryEndResult = eval(endResult);
console.log(endResult);
veryEndResult = newNode;
}
}
class LinkedListNode {
constructor (value, next) {
this.value = value;
this.next = next;
}
}
let linkedList = new LinkedList();
linkedList.addToHead(20);
linkedList.addToTail(30);
I have a class which creates a link list and also a function that adds nodes to that list . I am trying to implement more functions to the list but I want to see the changes these functions make by displaying the entire list .
this is the code :
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element) {
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function() {
return head;
};
this.add = function(element) {
var node = new Node(element);
if (head === null) {
head = node;
} else {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
After declaring a LinkedList class and adding elements with the class.add(element) function , how can I display the entire list with console.log() ?
You need to write the toString method of the LinkedList class. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
You could define a method toString in prototype object and loop through all the items.
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element) {
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function() {
return head;
};
this.add = function(element) {
var node = new Node(element);
if (head === null) {
head = node;
} else {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
}
LinkedList.prototype.toString = function() {
let head = this.head();
let result = [];
while(head) {
result.push(head.element);
console.log();
head = head.next;
}
return result.join(", ");
}
let list = new LinkedList();
list.add("test");
list.add("test2");
list.add("test3");
console.log(list.toString());
inserting single node to linked list giving me circular at the next value !!
hello there , i am learning how to create a linked list and test it with jest ,
as you can see in the photo my issue that its not stopping , from my understanding it should giving me a null at the end !
this how my conole.log looks like !
my test file :
'use strict' ;
const LL = require('../lib/linked-list.js');
describe('Linked-List Test' , () => {
it('Can properly insert into the linked list' , () => {
let list = new LL() ;
list.insert('test');
expect(list.head.name).toEqual('test');
});
});
my js file :
'use strict';
// const Node = require
function Node(value) {
this.name = value;
this.next = null;
}
class LinkedList {
constructor() {
this.head = null;
}
insert(value) {
let node = new Node(value);
if (!this.head) {
this.head = node;
}
// { name : test1 , next = null }
let pointer = this.head;
console.log(pointer);
console.log(pointer.next);
while (pointer.next) {
pointer = pointer.next;
}
console.log(node);
pointer.next = node;
console.log(pointer.next);
console.log(pointer.next.next);
console.log(pointer.next.next.next);
console.log(pointer.next.next.next.next);
return this;
}
include(value){
let pointer = this.head;
while (pointer.next) {
if(pointer.next.name === value){
return true ;
}
pointer = pointer.next;
}
return false ;
}
}
module.exports = LinkedList;
Try this. You have to add return in if (!this.head) condition. So it should not execute the code after this block.
"use strict";
// const Node = require
function Node(value) {
this.name = value;
this.next = null;
}
class LinkedList {
constructor() {
this.head = null;
}
insert(value) {
let node = new Node(value);
if (!this.head) {
this.head = node;
return this;
}
let pointer = this.head;
while (pointer.next) {
pointer = pointer.next;
}
pointer.next = node;
return this;
}
include(value) {
let pointer = this.head;
while (pointer.next) {
if (pointer.next.name === value) {
return true;
}
pointer = pointer.next;
}
return false;
}
}
let list = new LinkedList();
list.insert("test");
list.insert("test2");
console.log(list);
This is the pseudocode we have to build the LL from:
FUNCTION push(element)
CREATE node
SET node.value TO element
SET node.next TO null
IF the head node does not exist
THEN SET head to node
ELSE
SET current to head
SET current.next to node
END IF
END FUNCTION
The pseudocode itself has an error in it as well.
Below is my attempt to follow that, but right now it's pointing
to the { right after value in the push function.
let head = null,
last,
node,
current,
value = element;
const linkedList = () => {
let node = new Node(value);
push(value) {
if(head === null) {
head = last = node;
} else {
last.next = node;
last = node;
}
}
}
Error : push(value) { <----- This curly bracket is throwing the error. Unexpected token.
Beside the syntax error, you have a logical error as well. You need to treat the head node different from any other node and set the head property to node if not set, but if set, then assign to the last node the next node.
If you no head node, you can not set the last node, because there is actually no one.
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.last = null;
}
push(value) {
var node = new Node(value);
if (!this.head) {
this.head = node;
} else {
this.last.next = node;
}
this.last = node;
}
}
var ll = new LinkedList;
ll.push(10);
console.log(ll);
ll.push(11);
console.log(ll);
ll.push(12);
console.log(ll);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With check for an already inserted value.
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.last = null;
}
push(value) {
var node = new Node(value),
temp = this.head;
while (temp) {
if (temp.value === value) return;
temp = temp.next;
}
if (!this.head) {
this.head = node;
} else {
this.last.next = node;
}
this.last = node;
}
}
var ll = new LinkedList;
ll.push(10);
console.log(ll);
ll.push(11);
console.log(ll);
ll.push(12);
console.log(ll);
ll.push(11);
console.log(ll);
.as-console-wrapper { max-height: 100% !important; top: 0; }
And since we are at it.
Here is a version where you can insert append and remove nodes in ES6. No last node thougth since that would ruin the beauty of it. :)
class Node {
constructor(value) {
this.prev = null;
this.next = null;
this.value = value === undefined? null : value;
this.list = null;
}
remove() {
let prev = this.prev;
let next = this.next;
if (prev) {
prev.next = next;
}
if (next) {
next.prev = prev;
}
return this;
}
insert(node) {
let prev = this.prev;
if (prev) {
prev.next = node;
node.prev = prev;
}
this.prev = node;
node.next = this;
}
append(node) {
let next = this.next;
if (next) {
next.prev = node;
node.next = next;
}
this.next = node;
node.prev = this;
}
}
class LinkedList {
constructor() {
this.head = null;
}
get last() {
return this.list.length > 0 ? this.list[this.list.length] : null;
}
get values() {
let node = this.head;
let values = [];
while(node) {
values.push(node.value);
node = node.next;
};
return values;
}
push(node) {
node.prev = null;
node.next = null;
if (this.head) {
this.head.prev = node;
node.next = this.head;
}
this.head = node;
}
find(v) {
let node = this.head;
let fn = v;
if (!(v instanceof Function)) fn = (el) => el.value === v;
while(node && !fn(node)) {node = node.next;};
return node;
}
forEach(fn) {
let node = this.head;
while(node) {fn(node); node = node.next;};
}
}
Usable like so:
let ll = new LinkedList();
let n1= new Node(1);
let n2= new Node(2);
let n3= new Node(3);
ll.push(n1);
ll.push(n2);
ll.find(1).append(n3);
console.log(ll.values);
ll.find(3).remove();
console.log(ll.values);
ll.find(2).append(n3);
console.log(ll.values);
I am trying to implement circular linked list in javascript.
I just want to know is it the right way to implement this in javascript?
Are there any memory leaks or infinite object creation?
function LinkedList() {
this.Node = null;
this.count = 0;
this.head = null;
};
LinkedList.prototype.append = function (value) {
// create new node
var node = this.createNode(value);
console.log(value);
if (this.head == null) {
this.Node = node;
this.Node.next = null;
this.head = this.Node;
} else {
var ptr = this.Node;
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = node;
}
this.count++;
};
LinkedList.prototype.getSize = function () {
console.log(this);
};
LinkedList.prototype.close = function () {
var ptr = this.head;
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = this.head;
};
LinkedList.prototype.createNode = function (value) {
var node = {};
node.value = value;
node.next = null;
return node;
};
var li = new LinkedList();
li.append(1);
li.append(2);
li.append(3);
li.append(4);
li.close();
li.getSize();
When i checked the console, it displayed as head contains one node, and that node contains another node etc.
It it the reference or the actual object they are storing?
The way you did your append function seems slightly flawed to me... because exactly after it executes, your list is at an inconsistent state. You need to call close() in order to setup everything correctly. What i would suggest is that you can alter the append() function to dynamically update the head and tail according; thus you wouldn't need to call close().
Below is how I would have implemented the append() method (basically just slightly modifying your code):
LinkedList.prototype.append = function(value) {
var node = {
value: value,
next: this.head
};//cricular node
if (this.count === 0) {
this.head = {};
this.head.value = value;
this.head.next = this.head;
this.tail = this.head;
} else {
this.tail.next = node;
this.tail = node;
}
this.count++;
};
getCircular(start){
let i=0,j=0;
let secondHead = this.head;
let pointer = this.head;
let pointer2 = secondHead;
while(i<start){
let temp1 = pointer.next;
pointer = temp1;
i++;
}
this.head = pointer;
this.tail.next = pointer2;
while(j<start-1){
let temp2 = pointer2.next;
pointer2 = temp2;
j++;
}
this.tail = pointer2;
this.tail.next = null;
return this;
}
Suppose there is already a list as : Kohli -> Dhoni -> Yuvi -> Sharma -> Dhawan ,
And you pass an index of 2 , then the result will be like :
Yuvi -> Sharma -> Dhawan -> Kohli -> Dhoni
Then your call should be like : ll.getCircular(2); // ll is an object for example