Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

stack implementation in javascript using linked list

// Stack Implementation using LinkedList.

class StackNode{
    constructor(data) {
        this.data=data;
        this.next=null;
    }
}

var top =null;

function isEmpty() {
    if(top==null)
        console.log("Stack is Empty");
    else
        console.log("Stack is not empty");
}

function push(data){
    const newNode = new StackNode(data);
    if(top == null){
        top=newNode;
    } else{
        const temp = top;
        top=newNode;
        newNode.next =temp;
    }
}

function pop(){
    if(top == null){
        console.log("Stack is Empty");
    } else {
        var popped = top.data;
        top=top.next;
    }
    return popped;
}

function print(top){
    let p = top;
    str="";
    while(p!=null){
        str+=p.data+" ";
        p=p.next;
    }
    console.log("Elements in stack
", str);
}

function peek(){
    if(top == null){
        console.log("Stack is Empty");
    } else {
        return top.data;
    }
}

push(10);
push(20);
push(30);
push(40);
push(50);
console.log(pop()+" popped in stack");
console.log(peek()+" is top element in stack");
print(top);

// Time Complexity -> O(1)
// Space Complexity -> O(1)
Comment

PREVIOUS NEXT
Code Example
Javascript :: Shallow copy Objects using Object.prototype.assign method 
Javascript :: camel case first javascript 
Javascript :: proxmox local storage path 
Javascript :: yarn create react app in current directory 
Javascript :: find all even numbers javascript 
Javascript :: add clickable link to image in react native 
Javascript :: java.lang.IllegalArgumentException: Can only download HTTP/HTTPS 
Javascript :: random number generator 
Javascript :: react event listener 
Javascript :: react-with-firebase-auth 
Javascript :: angular router navigate inside setTimeout 
Javascript :: node js simple server 
Javascript :: discord.js v12 how to set owner commands 
Javascript :: nodejs sqlite create db if not exists 
Javascript :: how to disable menu bar in browser using javascript 
Javascript :: bind this react 
Javascript :: discord js check if message author is admin 
Javascript :: stop execution javascript 
Javascript :: javascript sort multi-dimensional array 
Javascript :: jquery daterangepicker using moment 
Javascript :: convert c# to javascript online 
Javascript :: useEfefct react 
Javascript :: svg clientx 
Javascript :: npm redis for js 
Javascript :: on enter to tab javascript 
Javascript :: JavaScript catch() method 
Javascript :: react native ant design 
Javascript :: webpack.config.js 
Javascript :: selectores de jquery 
Javascript :: multiple forms formData js 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =