I'm trying to implement a Java stack structure, but when I try to remove an element I get the following error:
> Exception in thread "main" java.lang.NullPointerException
at br.com.magnoliamedeiros.pilhafila.LinkedList.remove(LinkedList.java:17)
at br.com.magnoliamedeiros.pilhafila.Pilha.pop(Pilha.java:13)
at br.com.magnoliamedeiros.pilhafila.Program.main(Program.java:22)
Any idea what might be happening? (error lines are marked in code snippets)
My program:
//...
Pilha<String> pilha = new Pilha<String>();
//...
pilha.push("Márcia");
pilha.pop(); // LINHA #22
Class Pilha
:
public class Pilha<T> extends LinkedList<T>{
public void push(T valor){
add(valor);
}
public T pop() throws Exception{
if(isEmpty()){
throw new Exception("Pilha vazia!");
}
return this.remove(0); // LINHA #13
}
}
Class Node
:
public class Node<T> {
Node<T> proximo;
Node<T> anterior;
T valor;
public void setProximo(Node<T> proximo){
this.proximo = proximo;
}
public Node<T> getProximo(){
return proximo;
}
public void setAnterior(Node<T> anterior){
this.anterior = anterior;
}
public Node<T> getAnterior(){
return anterior;
}
public void setValor(T valor){
this.valor = valor;
}
public T getValor(){
return valor;
}
}
Class LinkedList
:
public class LinkedList<T> implements java.util.List<T>{
Node<T> inicio;
Node<T> fim;
int size = 0;
@Override
public T remove(int index) {
if(index==0){
inicio.getAnterior().setProximo(inicio.getProximo()); // LINHA #17
inicio.getProximo().setAnterior(inicio.getAnterior());
inicio.setAnterior(null);
inicio.setProximo(null);
return inicio.getValor();
}else{
int i = 1;
while(i!=this.size()){
i++;
inicio.setProximo(inicio.getProximo());
if(i == index){
inicio.getAnterior().setProximo(inicio.getProximo());
inicio.getProximo().setAnterior(inicio.getAnterior());
inicio.setAnterior(null);
inicio.setProximo(null);
return inicio.getValor();
}
}
}
return null;
}
public boolean add(T e){
Node<T> newNode = new Node<T>();
newNode.setValor(e);
if(inicio == null){
inicio = newNode;
}
if(fim == null){
fim = newNode;
}else{
fim.setProximo(newNode);
newNode.setAnterior(fim);
fim = newNode;
}
size++;
return true;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size==0;
}
}