3
I’m having trouble removing an item by the value of a simply chained list. I’m doing so:
class No{
public:
int dado;
No *next;
No(int item, No *ptr= NULL){
dado=item;
next=ptr;
}
};
class Lista{
public:
Lista(){
first = last = NULL;
};
bool listaVazia();
void inserirInicio(int item);
void inserirFim(int item);
void inserirPosicao(int item, int posicao);
void buscaItem(int item);
void removeInicio();
void removeFim();
void removeItem(int item);
void imprimirLista();
int tamanhoLista = 0;
private:
No *first, *last;
};
I can already check on the function if it is entering at the beginning and at the end, I need to understand how I will remove from a position in the middle so it does not get lost:
void Lista::inserirPosicao(int item,int posicao){
if(posicaoValida(posicao)){
if(posicao == 1){ // INSERI NA PRIMEIRA POSICAO
inserirInicio(item);
}else{
if(last->next == NULL){ // INSERI NA ULTIMA POSICAO
inserirFim(item);
return;
}else{ // INSERIR NO MEIO
}
}
}else{
cout << endl << " POSICAO INVALIDA" << endl;
}
}
Do you already have a method to go through the list? Can it find an item by its position? You need it first. Eliminating the last one is easy and I think you’re doing it, just undo it and obviously decrease the size. The problem is that you need to change the previous element of the list that it no longer has a next one. And since she’s not doubly chained you don’t have that information. Then you have to go through the entire list until you get to what was the penultimate element and undo the pointer from next.
– Maniero
Do not comment code, edit the question and put all the information you can. To delete just make it null.
– Maniero
@bigown in this last function removeItem(item) I need to locate the item and remove it, for this I did a while running and an if checking if the item matches a value, if yes I should remove it and make the previous point to the next in
– Gabriel Rodrigues
You changed the question. You need to access two items to remove: you have to figure out the item to be removed; you will get the
next
contained in it; will undo the whole node; will throw thenext
obtained in it and will change thenext
of the previous node with thisnext
, so the previous one will point to the next one. It’s pretty simple. I just don’t answer because I’m on a tight schedule right now and I can’t test. If you put a code that I can test I see if you can change what you need, if possible do in http://ideone.com/– Maniero
the code is made in two
.h
, here is the code: https://drive.google.com/open?id=0ByiDi-nlXfgVWHB3VzFPUE40Zk0&authuser=0– Gabriel Rodrigues