Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stack Comparison

Tags:

java

stack

I'm wondering how to accomplish this:

  1. Compare two Stack objects
  2. Do this recursively
  3. After the method that does this is complete, the Stacks remain as they were to begin with (i.e. same order, same items).

Only the push, pop and isEmpty methods for Stack is available.

I'm looking more for theoretical help than coding help, but any insight would be appreciated.

like image 314
user Avatar asked Mar 05 '13 17:03

user


People also ask

How do you compare two stacks?

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.

How do you compare two variables in Java?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.

Can Java stack have different data types?

If you are to implement the stack with arrays, then within the stack array you need to maintain a union so that you can store different data types. Along with this you need to have stack top variable and an array to keep track of data type of each array position. Here is the code.

What is stacking in Java?

A Stack is a Last In First Out (LIFO) data structure. It supports two basic operations called push and pop. The push operation adds an element at the top of the stack, and the pop operation removes an element from the top of the stack. Java provides a Stack class which models the Stack data structure.


1 Answers

Two stacks are identical if their top level elements are identical, and the remaining stacks are identical (namely, the recursive condition).

Now, think what to do just before returning from the method call, in order to leave the stacks the same way they where given at the invocation time.

---EDIT---

The working Java code (derived from Markus A. solution, but with an interesting use of "finally" and with generics):

static <T> boolean compareStacks(Stack<T> a, Stack<T> b) {
    if (a.isEmpty() != b.isEmpty()) return false; 
    if (a.isEmpty() && b.isEmpty()) return true; 
    T element_a = a.pop(); 
    T element_b = b.pop();
    try {
        if (((element_a==null) && (element_b!=null)) || (!element_a.equals(element_b)))
            return false;
        return compareStacks(a, b); 
    } finally { // restore elements
        a.push(element_a); 
        b.push(element_b);
    }
}
like image 52
Eyal Schneider Avatar answered Nov 11 '22 16:11

Eyal Schneider