Reputation: 11
Good night, I'm having trouble comparing the common values of a list and a stack, could you help me to solve this problem? Thank you very much in advance.
Note: I'm a beginner
public static void main(String[] args) {
Stack<Integer> pilha = new Stack<Integer>();
pilha.push(15);
pilha.push(20);
pilha.push(35);
pilha.push(45);
LinkedList<Integer> lista = new LinkedList<>();
lista.addLast(41);
lista.addLast(23);
lista.addLast(20);
lista.addLast(12);
System.out.println("Os numeros da Pilha são:" + pilha);
System.out.println("Os numeros da Pilha são:" + lista);
int sPilha = pilha.size();
int valor =0;
int valorLista = 0;
int verd = 0;
for(int cont =0; cont < sPilha; cont++) {
valor = pilha.pop();
valorLista = lista.pop();
if(valor == valorLista){
verd = valorLista;
System.out.println("Os valores em comum da lista são: " + valorLista);
}
}
}
}
Upvotes: 1
Views: 48
Reputation: 642
pop method removes the element from list or stack (read more here: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Stack.html#pop()).
If you don't want to remove element, access it using get method:
for(int cont = 0; cont < pilha.size(); cont++) {
valor = pilha.get(cont);
if(lista.contains(valor)) {
System.out.println("Os valores em comum da lista são: " + valor);
}
}
Upvotes: 0
Reputation: 511
Like wombat mentioned in the comment
for(int cont =0; cont < pilha.size(); cont++) {
valor = pilha.get(cont);
for(int i =0; i < lista.size(); i++) {
valorLista = lista.get(i);
if(valor == valorLista){
verd = valorLista;
System.out.println("Os valores em comum da lista são: " + valorLista);
}
}
}
Upvotes: 1