单链表的逆置
2016-05-06 10:53
239 查看
最近看了面试常问到的单链表逆置问题,做了一下总结。
第一种方法,使用三指针。
node *reverse(node *head)
{
node *p1,*p2,*p3;
if(head==NULL||head->next==NULL)
return head;
p1=head,p2=p1->next;
while(p2)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
head->next=NULL;
head=p1;
return head;
}
![](http://img.blog.csdn.net/20160506104849758?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
最后执行完循环后,记得让head->next = NULL; 让P1做head节点,即可实现逆置。
第二种方法,递归。
LNode* ReverList1(LNode* head)
{
if (head == NULL)
return NULL;
if (head->next == NULL)
{
return head;
}
LNode* Node = head; //保留上一个结点
LNode* Nex = head->next;
LNode* HeadNode = ReverList1(Nex);
Nex->next = Node; //逆置
Node->next = NULL; //这句必须有,否则会产生循环链表
return HeadNode;//返回逆置链表的尾结点
}
理解图如下
第一种方法,使用三指针。
node *reverse(node *head)
{
node *p1,*p2,*p3;
if(head==NULL||head->next==NULL)
return head;
p1=head,p2=p1->next;
while(p2)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
head->next=NULL;
head=p1;
return head;
}
最后执行完循环后,记得让head->next = NULL; 让P1做head节点,即可实现逆置。
第二种方法,递归。
LNode* ReverList1(LNode* head)
{
if (head == NULL)
return NULL;
if (head->next == NULL)
{
return head;
}
LNode* Node = head; //保留上一个结点
LNode* Nex = head->next;
LNode* HeadNode = ReverList1(Nex);
Nex->next = Node; //逆置
Node->next = NULL; //这句必须有,否则会产生循环链表
return HeadNode;//返回逆置链表的尾结点
}
理解图如下
相关文章推荐
- makefile---include的使用
- 常用SQL整理 - DENSE_RANK()
- 怪异的JAVA对象属性存储
- 知识普及:彻底搞懂CSS中单位px和em,rem的区别
- Netbeans使用技巧,从点滴提高编程效率
- Linux进程的睡眠和唤醒
- 第6届山东省浪潮杯 Circle of Friends SDUT3262
- 查找所有的文本文件然后打印出来
- 最新 Bitnami redmine安装与配置
- oracle 11g 之LogMiner分析重做日志实践
- ORACLE中将一列已有数据的字段类型进行改变的解决方案
- Action中获取web对象的方式
- Nginx的工作模式和一些理解
- GCD同步异步测试DEMO
- 饮食问题
- Dump调试之ExceptionCode
- VC中各数据类型所表示的范围和占用的字节数是多大?
- 线性表的顺序存储结构及该结构的插入与删除
- android sql语句大全
- php 之 数据访问 增删改查练习题