Given two Stacks, the task is to check if the given stacks are same or not.
Two stacks are said to be same if they contains the same elements in the same order.
- Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or not.
- First check if the size of given stack1 and stack2 are equal. If the size is not equal, set flag to false and return it.
- If the size is same, then compare the top elements of both of the given stacks.
- If the top of both stacks is NOT same, set flag to false and return it otherwise pop top elements of both stacks.
- Repeat step 3 and 4 until all elements are popped out from both of the stacks.
- If both stacks gets empty and the flag variable is still true, it means that the stacks are same.
Below is the implementation of the above idea:
Stacks are Same
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Implement two stacks in an array
- Iterative Postorder Traversal | Set 1 (Using Two Stacks)
- Bubble sort using two Stacks
- Merging and Sorting Two Unsorted Stacks
- Infix to Prefix conversion using two stacks
- Add two numbers represented by Stacks
- Queue using Stacks
- How to efficiently implement k stacks in a single array?
- Find maximum sum possible equal sum of three stacks
- Sorting array using Stacks
- Sudo Placement[1.3] | Playing with Stacks
- Maximize sum of topmost elements of S stacks by popping at most N elements
- Check if two expressions with brackets are same
- Maximize Sum possible by subtracting same value from all elements of a Subarray of the given Array
- Check if two trees are Mirror
- Check if concatenation of two strings is balanced or not
- Delete consecutive same words in a sequence
- Next greater element in same order as input
- Nodes from given two BSTs with sum equal to X
- Check if a given array can represent Preorder Traversal of Binary Search Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.