w3resource

JavaScript Exercises: Merge two stacks into one

JavaScript Stack: Exercise-20 with Solution

Merge Two Stacks

Write a JavaScript program to merge two stacks into one.

Sample Solution:

JavaScript Code:

class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }
  pop() {
    if (this.isEmpty()) {
      return "Underflow";
    }
    return this.items.pop();
  }
  peek() {
    return this.items[this.items.length - 1];
  }
  isEmpty() {
    return this.items.length === 0;
  }
  size() {
    return this.items.length;
  }
  
 merge(stack2) {
    let stack1 = this.items;
    while (stack2.length > 0) {
      stack1.push(stack2.pop());
    }
    return stack1;
  }
  
displayStack(stack) {
  console.log("Stack elements are:");
  let str = "";
  for (let i = 0; i < stack.items.length; i++)
    str += stack.items[i] + " ";
  return str.trim();
 }      
}
let stack1 = new Stack();
stack1.push(10);
stack1.push(20);
stack1.push(30);
console.log("Stack-1");
console.log(stack1.displayStack(stack1));
let stack2 = new Stack();
stack2.push(40);
stack2.push(50);
stack2.push(60);
stack2.push(70);
console.log("Stack-2");
console.log(stack2.displayStack(stack2)); 
let result_merged_stack = stack1.merge(stack2.items); 
console.log("Merged Stack:");
console.log(result_merged_stack);

Sample Output:

Stack-1
Stack elements are:
10 20 30
Stack-2
Stack elements are:
40 50 60 70
Merged Stack:
[10,20,30,70,60,50,40]

Flowchart:

Flowchart: JavaScript  Exercises: Merge two stacks into one.
Flowchart: JavaScript  Exercises: Merge two stacks into one.
Flowchart: JavaScript  Exercises: Merge two stacks into one.

Live Demo:

See the Pen javascript-stack-exercise-20 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that merges two stacks (arrays) into one while preserving the order of elements from both stacks.
  • Write a JavaScript function that combines two stacks and eliminates duplicate elements in the merged result.
  • Write a JavaScript function that interleaves elements from two stacks to form a new merged stack.
  • Write a JavaScript function that validates both stacks and returns a new stack containing all elements from the input stacks.

Go to:


PREV : Move Nth from Bottom to Top.
NEXT : Linked List Stack Implementation.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.