everybody. How can I check if 2 stacks has the same values?
For example, in stack1 I have [1,3,4,5] and in stack2 I have [4,3,1,5], so the stacks has the same values and the methood needs to return true.
In addition, the stacks must be (in the end) as they were given (with the original values and the same order).
I have started to work on it but unfortuantely it’s not working good:
import java.util.Stack; public class StackMain { public static void main(String[] args) { Stack<Integer> st1 = new Stack<Integer>(); st1.push(2); st1.push(643); st1.push(254); st1.push(13); st1.push(74); st1.push(6); st1.push(5); st1.push(99); Stack<Integer> st2 = new Stack<Integer>(); st2.push(643); st2.push(2); st2.push(254); st2.push(13); st2.push(99); st2.push(5); st2.push(6); st2.push(74); System.out.println(isSameStacks(st1,st2)); } public static boolean isSameStacks(Stack st1, Stack st2) { Stack st1Reverse = new Stack(); Stack st2Reverse = new Stack(); boolean isExist = false; while(st1.isEmpty()==false) { isExist = false; st1Reverse.push(st1.pop()); while(st2.isEmpty()==false) { st2Reverse.push(st2.pop()); if(st1Reverse.peek()== st2Reverse.peek()) isExist = true; } while(st2Reverse.isEmpty()==false) st2.push(st2Reverse.pop()); if(isExist!=true) { while(st1Reverse.isEmpty()==false) st1.push(st1Reverse.pop()); return false; } } while(st1Reverse.isEmpty()==false) st1.push(st1Reverse.pop()); return true; }
Thanks in advance.
Advertisement
Answer
One simple way is to use the Collection
functionality:
public static boolean isSameStacks(Stack st1, Stack st2) { if(st1.size() != st1.size()) return false; List list = new ArrayList<>(st1);//add all st1 elements list.removeAll(st2);//remove all st2 elements return list.size() == 0; }
For completeness here is another solution using Collection
functionality. It is based on the partial solution posted by @user7:
public static boolean isSameStacks(Stack st1, Stack st2) { return st1.size() == st1.size() && new HashSet<>(st1).equals(new HashSet<>(st2)); }