I want to implement a method that deletes the elements in the stack this that are equal to the elements in the stack s given as an argument.
I tried to do something but it didn't work. I have s1 and s2 that are temporary stacks, what I think I'm doing is that I'm popping the stack top of this and s and then compare them to check if they are equal, but I'm not getting the desired result.
input:
this: -5
4
3
3
1
s: 7
6
4
3
1
output: 3
1
This is my code:
public void deleteEqualToOther(Stack s) {
Stack s1 = new Stack();
Stack s2 = new Stack();
while(!this.isEmpty() && !s.isEmpty()) {
if(this.stackTop() == s.stackTop())
s1.push(this.stackTop());
this.pop();
s2.push(s.stackTop());
s.pop();
}
while(!s1.isEmpty()) {
this.push(s1.stackTop());
s1.pop();
}
}