Find out length of linked list in node js
Js program for Find out length of linked list. Here problem description and explanation.
// Node JS Program for
// Find the length of linked list
// Linked list node
class LinkNode
{
constructor(value)
{
this.data = value;
this.next = null;
}
}
class SingleLL
{
constructor()
{
this.head = null;
this.tail = null;
}
// Insert new node at the last
insert(value)
{
// Create new node
var node = new LinkNode(value);
if (this.head == null)
{
this.head = node;
}
else
{
// Add new node at the end
this.tail.next = node;
}
this.tail = node;
}
// Count number of nodes and
// returns the number of nodes
findLength()
{
var temp = this.head;
var count = 0;
while (temp != null)
{
// Visit to next node
temp = temp.next;
// Increase the node counter
count++;
}
return count;
}
// Display all Linked List elements
display()
{
if (this.head != null)
{
process.stdout.write("Linked List Element :");
var temp = this.head;
while (temp != null)
{
process.stdout.write(" " + temp.data);
temp = temp.next;
}
}
else
{
console.log("Empty Linked list");
}
}
}
function main()
{
var task = new SingleLL();
task.insert(5);
task.insert(10);
task.insert(15);
task.insert(20);
task.insert(25);
task.insert(30);
task.insert(35);
task.display();
console.log("\nLength : " + task.findLength());
}
// Start program execution
main();
Output
Linked List Element : 5 10 15 20 25 30 35
Length : 7
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment