倒序单链表
近来一些公司笔试时有这题,随手写一下
算法:
A. 首先保存1的next(即链表前进一个位置到2),然后1的next指向空作为倒序后的最后一个,从此时此刻1起,1相邻右边成员的next指向的地址与前一个(左边一个)成员的地址交换.交换后1的地址被3替换(即1到3的位置),变成3,2的next指向1的地址.
B. 此时再将2与3地址互换,再次形成A部份的情况.
用此方法反转链表,看起来似间隔一个链表成员交换地址,形像表示如下:
1 2-3-4-5-6 1与3交换
1-2 3-4-5-6 2与4交换
1-2-3 4-5-6 3与5交换
1-2-3-4 5-6 4与6交换
1-2-3-4-5 6 2与4交换
C. 最后一步将6的next人工指向5,完工.
结果如下图所示:


D. 总结下,要是链表长为1000,那么会调用swap1996次,效率较低占用时间较多,而且伴随大量的强制类型转换与异或运算,虽然只用了一个变量,但效率明显不高,权当学习了使用指针的指针的强制类型转换来参与的地址的异或运算.对函数传参,地址的处理,链表的运用有了更为深入的了解.
E. 附代码:
// 单链表倒序.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
struct list{int data;list* next;};
list* createlist()
{
list *head=new list,*p=head;
for(int temp=1;temp<1000;temp++)
{
p->data=temp;
p->next=new list;
p=p->next;
p->data=temp+1;
p->next=0;
}
return head;
}
void swap(list** a,list** b)
{
*a=(list*)((int)*a^(int)*b);
*b=(list*)((int)*a^(int)*b);
*a=(list*)((int)*a^(int)*b);//head=rehead^head;rehead=rehead^head;//swap
}
list* ReverseList(list* head)
{
list *rehead=head;
head=head->next;
rehead->next=0;
while(head->next)
{
swap(&rehead,&head->next);
swap(&rehead,&head);
}
head->next=rehead;
return head;
}
list* head=createlist();
list* rehead=ReverseList(head);