[size=large]将一个链表按逆序排列,即将链头当链尾,链尾当链头[/size]
#include<stdio.h>
struct Node
{
int data;
struct Node *next;
};
//创建链表
struct Node *create(int n,int count)
{
int i;
struct Node *head,*p1,*p2;
head = p1 = p2 = (struct Node*)malloc(sizeof(struct Node));
head->data = n;
for(i=1; i<count; i++)
{
p1 = (struct Node*)malloc(sizeof(struct Node));
p1->data = i+n;
p2->next = p1;
p2 = p1;
}
p2->next = NULL;
return head;
}
//链表逆序(用两个指针跑到后面往前指)
struct Node *reverse(struct Node *p)
{
struct Node *p1,*p2,*head;
p1 = p2 = head = p;
while(p != NULL)
{
p = p->next;
if(p1 == head)
{
p1->next = NULL;
}
else
{
p1->next = p2;
}
p2 = p1;
p1 = p;
}
return p2;
}
void main()
{
struct Node *p,*head;
//创建链表
head = p = create(3,5);
printf("链表初始数据:\n");
while(p)
{
printf("%d\n", p->data);
p = p->next;
}
p = head;
printf("\n逆转链表:\n");
p = reverse(p);
while(p)
{
printf("%d\n", p->data);
p = p->next;
}
}