leetcode记录 Reverse Linked List
2016-05-13 20:40
316 查看
链表逆转递归方式:
注意这里的返回的是tou.next,如果直接返回tou的话,或者在recursive函数中给tou赋值为head的话,得不到正确结果(引用也是值传递)
上面这种方法首先获取到尾节点,然后逐层返回该尾节点作为头节点,后面两条语句:p.next.next=p;和p.next一个是来做链表逆置的一个是用来断开原来的连接的
稍微有点复杂,但是画个图就明白了。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head; ListNode tou = new ListNode(0); recursive(head,tou).next = null; return tou.next; } private ListNode recursive(ListNode head,ListNode tou){ if(head.next==null||head==null){ tou.next=head; return head; } if(head.next!=null){ ListNode ln = recursive(head.next,tou); ln.next=head; } return head; } }
注意这里的返回的是tou.next,如果直接返回tou的话,或者在recursive函数中给tou赋值为head的话,得不到正确结果(引用也是值传递)
public class Solution { public ListNode reverseList(ListNode head) { if(head==null) return head; ListNode p=head; if(p.next==null){ return p; } else{ ListNode t=reverseList(p.next); p.next.next=p; p.next=null; return t; } } }
上面这种方法首先获取到尾节点,然后逐层返回该尾节点作为头节点,后面两条语句:p.next.next=p;和p.next一个是来做链表逆置的一个是用来断开原来的连接的
稍微有点复杂,但是画个图就明白了。
相关文章推荐
- 两个多项式相乘 使用散列表加速 在计算时合并多项式的项
- 构建之法阅读笔记05
- redis 数据类型详解 以及 redis适用场景场合
- 广场街拍白裙美女
- hdu 1372 Knight Moves(BFS)
- 每个程序员都应该了解的内存知识
- 杭电试题简单分类
- hdu2830 Matrix Swapping II(DP)
- zoj-3735 Josephina and RPG[概率dp]
- HDU 1014 Uniform Generator【公约数】
- 【百度之星】-IP聚合
- 数据库性能优化之SQL语句优化
- 人月神话阅读笔记02
- 薛定谔猫的疑问
- 战略游戏_ssl1230_树形dp
- Introduction to replication 翻译
- C# 按钮添加事件
- 数据库utf-8
- 第十一周项目3.1—警察和厨师
- Bluemix使用与其他云平台对比