我有一个链表,现在我想遍历它,每次前进时,我都会将当前节点移动到链表的开头,如下所示:
4 5 3 2 7
5 4 3 2 7
3 5 4 2 7
2 3 5 4 7
7 2 3 5 4
编码:
#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 *nod2 = NULL;
node *nod_tmp = NULL;
node *nod_next = NULL;
node *nod_before = NULL;
printf("Enter n: ");
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
nod_tmp = (node *)malloc(sizeof(node));
scanf("%d", &nod_tmp->p);
if (i == 0)
{
nod = nod2 = nod_tmp;
}
nod2->next = nod_tmp;
nod2 = nod_tmp;
}
nod_tmp = nod;
while (nod_tmp->next != NULL)
{
nod_before = nod_tmp; // save current node
nod_next = nod_tmp->next->next; // save next node
nod_before->next = nod_next; // link the previous with the next one
nod_tmp->next = nod; // point the current node to the beginning of list
}
while(nod != NULL)
{
printf("%d\n", nod->p);
nod = nod->next;
}
return 0;
}