Reputation: 115
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();
}
}
Upvotes: 2
Views: 53
Reputation: 1527
I'm not sure this is what you are asking for but.. You could iterate over your Stack, popping each element as you do. If the element appears in the other Stack then you discard it otherwise you add it to a temporary Stack. Once done, your Stack is empty and your temp Stack contains all the elements that were in your Stack but do not appear in the other Stack. Iterate over the temp Stack popping the elements and put them back into your Stack.
public void deleteEqualToOther(Stack other) {
Stack temp = new Stack();
while (! isEmpty()) {
int value = pop();
if (! other.contains(value)) {
temp.put(value);
}
}
while (! temp.isEmpty()) {
put(temp.pop());
}
}
Upvotes: 1