Thursday, 26 April 2018

Reverse a linked list - JavaScript

linked list is a linear data structure where each element is a separate object. Each element (we will call it a node) of a list is comprising of two items - the data and a reference to the next node. The last node has a reference to null. The entry point into a linked list is called the head of the list.

If Linked List is :  22->45->67
Then, reverse Linked List is: 67->45->22


EXAMPLE:


class Node{
constructor(data){

this.data=data;
this.next=null;
}
}
class LinkedList{
constructor(){
this.root=null;
}
insertNode(data){
var newnode=new Node(data);
if(this.root===null){
this.root=newnode;
return;
}
var tempnode=this.root;
while(tempnode.next!==null){
tempnode=tempnode.next;
}
tempnode.next=newnode;
}
traverse(){
var tempnode=this.root;
console.log("\nThe linked list is: \n\n");
while(tempnode!==null){
console.log(tempnode.data);
tempnode=tempnode.next;
}
}
reverse(){
var currentnode=this.root;
var prevnode=null;
var nextnode;
while(currentnode!==null){
nextnode=currentnode.next;
currentnode.next=prevnode;
prevnode=currentnode;
currentnode=nextnode;
}
this.root=prevnode;
}
}
var ll=new LinkedList();
ll.insertNode(34);
ll.insertNode(56);
ll.insertNode(76);
ll.insertNode(90);
ll.traverse();
ll.reverse();
ll.traverse();

OUTPUT:




EmoticonEmoticon