• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Reverse Linked List

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

基本迭代

Time: O(N), Space: O(1)

 1 class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if (head == null) return null;
 4         ListNode p1 = head;
 5         ListNode p2 = head.next;
 6         while (p2 != null) {
 7             ListNode next = p2.next;
 8             p2.next = p1;
 9             p1 = p2;
10             p2 = next;
11         }
12         head.next = null;
13         return p1;
14     }
15 }

 

基本递归

Time: O(N), Space: O(N)递归栈大小

 1 class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if (head == null) return null;
 4         List<ListNode> res = new ArrayList<>();
 5         res.add(null);
 6         reverse(head, res);
 7         return res.get(0);
 8     }
 9     
10     public ListNode reverse(ListNode node, List<ListNode> res) {
11         if (node.next == null) {
12             res.set(0, node);
13             return node;
14         }
15         ListNode afterReverse = reverse(node.next, res);
16         afterReverse.next = node;
17         node.next = null;
18         return node;
19     }
20 }

 

posted @ 2015-12-15 11:15  neverlandly  阅读(268)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3