我有一个以这些值为例的链表:4 5 3 2 7,现在我想将每个节点与前一个节点交换,如下所示:
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
但不幸的是,当我解析输出时,我陷入了无限循环:
#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;
}