I need to develop a doubly linked list in which I can't specify my *prev and *next pointers, they have to be *A and *B, because they may assume each others functions as I tamper with the list. It is probably called a symmetric list in english.
I am having trouble inserting a node in this list. The program crashes (probably a segfault), and I don't know why, because I did use a special case for when the list is empty (if(atual == NULL)). The program is not over yet, there is more to implemente, so don't mind the stuff inside the switch that you don't see implemented yet. One more thing: each node has *A or *B to go along the list. That is why I check which one is looking back, in order to use the other one to go forward.
Sample input:
i 0 1.2
i 1 2.3
i 2 3.4
Here's the code:
#include<stdio.h>
#include<stdlib.h>
typedef struct no {
double num;
struct no *A;
struct no *B;
} no;
typedef struct lista {
no *cabo;
no *rabo;
} lista;
lista* criar(void) {
lista *L = malloc(sizeof(lista));
L->cabo = NULL;
L->rabo = NULL;
return L;
}
void inserir(lista *L, int posicao, double num) { //testar se funciona e verificar com pad se eh o melhor modo.
no *novo = malloc(sizeof(no));
no *atual, *aux;
atual = L->cabo;
aux = NULL;
char ref;
int i;
if (atual == NULL) { //a lista nao tem elementos
novo->A = L->cabo; //inserindo primeiro elemento, que tem contato tanto com a cabeca quanto com o rabo
novo->B = L->rabo;
L->cabo = novo;
L->rabo = novo;
return;
}
for (i = 0; i != posicao; i++) {
if (atual->A == aux) { //entao A aponta para tras. Para prosseguir uso B.
aux = atual;
atual = atual->B;
ref = 'B'; //o no para onde aux aponta tem seu proximo em B
}
else {
aux = atual;
atual = atual->A;
ref = 'A'; //o no para onde aux aponta tem seu proximo em A
}
}
if(ref == 'B') {
novo->B = aux->B;
aux->B = novo;
if (atual->A == aux) {
atual->A = novo;
}
else {
atual->B = novo;
}
novo->A = aux;
}
else if(ref == 'A') {
novo->B = aux->A;
aux->A = novo;
if (atual->A == aux) {
atual->A = novo;
}
else {
atual->B = novo;
}
novo->A = aux;
}
}
void reverter(lista *L, int inicio, int fim) {
}
int main(void) {
lista *L = criar();
char comando;
int posicao, inicio, fim;
double num;
while(1) {
scanf("%c", &comando);
if(comando == 't') break;
switch(comando) {
case 'i' : scanf("%d", &posicao);
scanf("%lf", &num);
inserir(L, posicao, num);
break;
//case 'p' : imprimir(L);
break;
case 'v' : scanf("%d", &inicio);
scanf("%d", &fim);
reverter(L, inicio, fim);
break;
}
}
return 0;
}