Flatten a folded linked list in node js
Js program for Flatten a folded linked list. Here more information.
/*
Node JS program for
Unfold a folded linked list OR
flatten folded linked list
*/
// Linked list node
class LinkNode
{
constructor(data)
{
this.data = data;
this.next = null;
}
}
class SingleLL
{
constructor()
{
this.head = null;
}
// Insert node at the beginning of linked list
addNode(data)
{
// Create node
var node = new LinkNode(data);
node.next = this.head;
// Set new head
this.head = node;
}
// Display linked list element
display()
{
if (this.head == null)
{
return;
}
var temp = this.head;
// iterating linked list elements
while (temp != null)
{
process.stdout.write(" " + temp.data + " →");
// Visit to next node
temp = temp.next;
}
console.log(" NULL");
}
// This is handle the request of unfold given linked list nodes
unfoldList()
{
if (this.head == null)
{
console.log("\n Empty linked list");
return;
}
var temp = this.head;
var auxiliary = null;
var hold = null;
// Loop which is separating the fold elements
while (temp.next != null)
{
// Get the second element
hold = temp.next;
if (hold.next != null)
{
// When exists pair of three elements
temp.next = hold.next;
// Visit to 3rd element
temp = hold.next;
}
else
{
// When get last two elements
temp.next = null;
}
// Add new node at beginning of auxiliary linked list
hold.next = auxiliary;
// Make new head node
auxiliary = hold;
}
if (temp != null)
{
// Combine lists
temp.next = auxiliary;
}
}
}
function main()
{
// Create a empty linked lists
var sll1 = new SingleLL();
var sll2 = new SingleLL();
// Constructed first linked list
// 2 → 5 → 1 → 8 → 10 → 4 → 9 → 7 → NULL
sll1.addNode(7);
sll1.addNode(9);
sll1.addNode(4);
sll1.addNode(10);
sll1.addNode(8);
sll1.addNode(1);
sll1.addNode(5);
sll1.addNode(2);
// Constructed second linked list
// 1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
sll2.addNode(7);
sll2.addNode(6);
sll2.addNode(5);
sll2.addNode(4);
sll2.addNode(3);
sll2.addNode(2);
sll2.addNode(1);
// Test A
console.log(" Before unfold");
sll1.display();
sll1.unfoldList();
console.log(" After unfold");
sll1.display();
// Test B
console.log(" Before unfold");
sll2.display();
sll2.unfoldList();
console.log(" After unfold");
sll2.display();
}
// Start program execution
main();
Output
Before unfold
2 → 5 → 1 → 8 → 10 → 4 → 9 → 7 → NULL
After unfold
2 → 1 → 10 → 9 → 7 → 4 → 8 → 5 → NULL
Before unfold
1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
After unfold
1 → 3 → 5 → 7 → 6 → 4 → 2 → NULL
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