思路:遍历一遍链表,利用一个辅助指针,存储遍历过程中当前指针指向的下一个元素,然后将当前节点元素
的指针翻转后,利用已经存储的指针往后面继续遍历。
------------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
typedef struct llist{
int data;
struct llist *next;
}node,*link;
link createlist(int *array,int n)//创建链表
{
link head;
link ptr,ptr1;
int i;
head=(link)malloc(sizeof(node));
if(!head)
{
printf("out of memory!\n");
exit(1);
}
ptr=head;
printf("请输入你要输入的链表==>\n");
for(i=0;i<n;i++)
{
ptr1=(link)malloc(sizeof(node));
if(!ptr1)
{
printf("out of memory!\n");
exit(1);
}
scanf("%d",&array[i]);
ptr1->data=array[i];
ptr1->next=NULL;
ptr->next=ptr1;
ptr=ptr1;
}
return head;
}
link reverselist(link head)//链表逆序
{
if(head->next==NULL||head->next->next==NULL)//如果为空或者只有一个元素,直接返回
{
return head;
}
link temp;
link ptr1,ptr2;
ptr1=head->next;
ptr2=head->next->next;
while(ptr2)
{
temp=ptr2->next;
ptr2->next=ptr1;
ptr1=ptr2;
ptr2=temp;
}
head->next->next=NULL;
head->next=ptr1;
return head;
}
void printlist(link head)//输出链表
{
link ptr;
ptr=head->next;
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->next;
}
printf("\n");
}
void main()
{
link head;
int array[5];
head=createlist(array,5);
printlist(head);
reverselist(head);
printf("逆序后的链表为:\n");
printlist(head);
}