My nodes have an integer value. And I want my program to swap two nodes by using such value:
void reemplazarNodosConValores(int a,int b) {
node *antecedenteDelPrimero = antecedentePorValor(a);
node *antecedenteDelSegundo = antecedentePorValor(b);
node *primero = nodoPorValor(a);
node *segundo = nodoPorValor(b);
node *nextDelPrimero = siguienteNodo(primero);
node *nextDelSegundo = siguienteNodo(segundo);
antecedenteDelSegundo->next = primero;
primero->next = nextDelSegundo;
antecedenteDelPrimero->next = segundo;
segundo->next = nextDelPrimero;
}
As you can see, I create six variables. The two nodes. The nodes before each one. And the nodes after each one.
Then, I do the swap.
However, swapping seem to generate an infinite loop when I try to print my nodes.
I based my swaps on this answer: https://stackoverflow.com/a/1536011/555690
EDIT: The other functions, as requested:
node *antecedentePorValor(int x) {
node *resultado = NULL;
for (int i = 0; i < counter; ++i) {
resultado = siguienteNodo(resultado);
if (siguienteNodo(resultado)) {
if (siguienteNodo(resultado)->data == x) {
break;
}
}
}
return resultado;
}
node *nodoPorValor(int x) {
node *resultado = head;
for (int i = 1; i < counter; ++i) {
if (resultado->data == x) {
break;
}
resultado = resultado->next;
}
return resultado;
}
node *siguienteNodo(node *nodo) {
node *resultado;
if (nodo) {
resultado = nodo->next;
}else{
resultado = head;
}
return resultado;
}
There are several cases you need to be careful with
bimmediately follows the node with valueaor vice-versaaorbis the first node in the listaor valuebNot possible to say whether you have a problem with case 2 or 3 without seeing the code for the functions
antecedentePorValorandnodoPorValor. There is a bug with case #1.Edit: to show why there is a bug with #1, assume node(a) points to node(b), then
In the comments I used shorthand
prevato meanantecedenteDelPrimeroandato meanprimeroandbto meansegundo.