LeetCode Reverse Linked List
2015-08-22 04:15
411 查看
原题链接在这里:https://leetcode.com/problems/reverse-linked-list/
Iteration 方法:
生成tail = head, cur = tail, while loop 的条件是tail.next != null. 最后返回cur 就好。
Time O(n), Space O(1).
AC Java:
Recursion 方法:
reverseList(head.next)返回的是从head.next开始的reverse list,把head加在他的尾部即可。
他的尾部恰巧是之前的head.next, 这里用nxt表示。
Recursion 终止条件是head.next == null, 而不是head == null, head==null只是一种corner case而已。
此种方法Time Complexity: O(n), 先下去再回来一共走两遍. Space O(n), 迭代用了stack一共O(n)大小。n 是原来list的长度。
AC Java:
跟上Reverse Nodes in k-Group.
Iteration 方法:
生成tail = head, cur = tail, while loop 的条件是tail.next != null. 最后返回cur 就好。
Time O(n), Space O(1).
AC Java:
/** * 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 tail = head; ListNode cur = head; ListNode pre; ListNode temp; while(tail.next != null){ pre = cur; cur = tail.next; temp = cur.next; cur.next = pre; tail.next = temp; } return cur; } }
Recursion 方法:
reverseList(head.next)返回的是从head.next开始的reverse list,把head加在他的尾部即可。
他的尾部恰巧是之前的head.next, 这里用nxt表示。
Recursion 终止条件是head.next == null, 而不是head == null, head==null只是一种corner case而已。
此种方法Time Complexity: O(n), 先下去再回来一共走两遍. Space O(n), 迭代用了stack一共O(n)大小。n 是原来list的长度。
AC Java:
/** * 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) { //Method: Recursion if(head == null || head.next == null){ return head; } ListNode nxt = head.next; ListNode newHead = reverseList(nxt); nxt.next = head; head.next = null; return newHead; } }
跟上Reverse Nodes in k-Group.
相关文章推荐
- [LeetCode#47]Permutations II
- shell脚本中一些特殊符号
- 使用wget 命令下载JDK的方法
- 操作队列
- XPath入门教程
- NGUI的代码控制
- 跳台阶解析【剑指Offer】
- uva11992区间修改线段树
- Mybatis 中 if test字符串比较问题
- android 比较靠谱的图片压缩
- mybatis动态SQL语句
- Mybatis的if test字符串比较问题
- node + Express 服务器性能实验
- XPath 多条件查询语句
- iOS链式编程框架介绍之LinkBlock(iOS链式编程)
- Ambari在线repo安装
- 正则表达式编程实例
- MyBatis参数传入集合之foreach动态sql
- Ambari离线安装
- MR案例:外连接代码实现