Implementacja stosu w JavaScript przy użyciu listy powiązanej
// 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\n", 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)
Aayush