zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    P1158 导弹拦截
    麦基数(p1045)
    Django之路由层
    web应用与http协议
    Django之简介
    Mysql之表的查询
    Mysql之完整性约束
    Mysql之常用操作
    Mysql之数据类型
    Mysql之数据库简介
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5047570.html
Copyright © 2011-2022 走看看