zoukankan      html  css  js  c++  java
  • Reverse Linked List 解答

    Question

    Reverse a singly linked list.

    Solution 1 -- Iterative

    Remember to set head.next = null or it will report "memory limit exceeds" error.

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode reverseList(ListNode head) {
    11         ListNode current = head, prev = head, post = head;
    12         if (current == null || current.next == null)
    13             return current;
    14         current = current.next;
    15         head.next = null;
    16         while (current.next != null) {
    17             post = current.next;
    18             current.next = prev;
    19             prev = current;
    20             current = post;
    21         }
    22         current.next = prev;
    23         return current;
    24     }
    25 }

    Solution 2 -- Recursive

    We can also use recursion to solve this problem.

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode reverseList(ListNode head) {
    11         if (head == null || head.next == null)
    12             return head;
    13         ListNode second = head.next;
    14         head.next = null;
    15         ListNode newHead = reverseList(second);
    16         second.next = head;
    17         return newHead;
    18     }
    19 }
  • 相关阅读:
    Document
    Document
    Document
    Document
    #开头的 十六进制颜色代码(#1B253A) 转成 rgba (rgba(27,37,58,0.5)) 格式
    网上找的,用 css 实现的酷炫效果
    git命令:全局设置用户名邮箱配置
    用 ice 搭建 react-hook 项目
    每天学点英语单词第一篇
    umi -- 震惊!umi 路由竟然如此强大!
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4812019.html
Copyright © 2011-2022 走看看