逆序函数:
NODE *reverse(NODE *head)
{
NODE *p1, *p2, *temp;
p1 = head;
p2 = head->next;
p1->next = NULL;
while(p2 != NULL)
{
temp = p2->next;
p2->next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
测试程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct link
{
int num;
struct link *next;
}NODE;
NODE *create(int n)
{
NODE *p, *head = NULL, *mov;
int i = 0;
for(i=0; i<n; i++)
{
p = (NODE *)malloc(sizeof(NODE));
printf("please input num:\n");
scanf("%d", &p->num);
if(i == 0)
{
head = p;
p->next = NULL;
}
else
{
mov = head;
while(mov->next != NULL)
{
mov = mov->next;
}
mov->next = p;
p->next = NULL;
}
}
return head;
}
NODE *reverse(NODE *head)
{
NODE *p1, *p2, *temp;
p1 = head;
p2 = head->next;
p1->next = NULL;
while(p2 != NULL)
{
temp = p2->next;
p2->next = p1;
p1 = p2;
p2 = temp;
}
return p1;
}
void display(NODE *head)
{
NODE *p = head;
while(p->next != NULL)
{
printf("%d ", p->num);
p = p->next;
}
printf("%d\n", p->num);
}
int main(int argc, char *argv[])
{
NODE *head = NULL;
head = create(5);
display(head);
head = reverse(head);
display(head);
return 0;
}