I have a linked list with this values as examples: 4 5 3 2 7, now I want to swap each node with previous one, like this:
4 5 3 2 7 // this beginning of list
5 4 3 2 7
5 3 4 2 7
5 3 2 4 7
5 3 2 7 4 // the list should now become like this
But unfortunately when I parse for the output I stuck in infinite loop:
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int p;
struct _node *next;
} node;
main(int argc, char **argv)
{
int i, n;
node *nod = NULL;
node *nod_tmp = NULL;
node *nod2 = NULL;
printf("Enter n: ");
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
nod_tmp = (node *)malloc(sizeof(node));
scanf("%d", &nod_tmp->p);
nod_tmp->next = nod;
nod = nod_tmp;
}
i = 0;
while(i < n)
{
nod_tmp = nod;
nod = nod->next;
nod->next = nod_tmp;
++i;
}
while(nod != NULL)
{
printf("%d\n", nod->p);
nod = nod->next;
}
return 0;
}
Your swap code is wrong. Should be something like this:
Or, since swapping every pair basically pushes the first element to the end you can do this:
Also, you may want to look at your input code. As written it will build the list with the values in reverse order as entered, because it’s always adding the next value to the head of the list.
Update
To avoid potential seg_faults the first loop above can be rewritten without the counter like this:
Update 2
Here’s full code that does what you want. Rather than swap each pair of nodes it just pushes the first node to the end of the list. I’ve also fixed the input loop so the list gets built in the correct order.