【问题标题】:java: Memory Limit Exceeded?java:超出内存限制?
【发布时间】:2018-09-21 00:52:28
【问题描述】:

我在leetCode中用java写了一段代码,链接如下: https://leetcode.com/problems/reverse-linked-list/description/

它显示“超出内存限制”,谁能解释原因?(您可以将我的代码粘贴到上面的链接中查看错误)

我的代码如下:

  public static class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
   }


public ListNode reverseList(ListNode head) {
    if(head ==null)
        return head;
    if(head.next ==null){
    return head;
    }
    Stack<ListNode> mStack =new Stack<>();
    while(head!=null){
        mStack.push(head);
        head = head.next;

    }
    ListNode mNode = new ListNode(0);
    ListNode result =mNode;
    while(!mStack.empty()){
       ListNode temp =  mStack.pop();;
        mNode.next = temp;
        mNode = mNode.next;

    }
    return result.next;

}

【问题讨论】:

  • 鉴于您描述的问题本质上是运行时,因此如果没有任何可运行的代码,很难在此处提供上下文。
  • 你可以把我的代码粘贴到上面的leetcode链接中查看结果

标签: java memory


【解决方案1】:

问题是,假设输入是 1->2->3。那么你将返回的是 3->2->1->2->1->2..... 这个循环链表在调用toString方法时会导致Memory Limit Exceeded。 要解决这个问题,只需将原始头部的 next 设置为 null。

【讨论】:

    【解决方案2】:

    这是因为他们希望您以恒定的空间复杂度来做这件事。一个简单的递归解决方案是:

    class Solution {
    
    
    
    public ListNode reverseList(ListNode head) {
        if (head==null){
            return head;
        }
        return reverseList(head,null);
    }
    
    public ListNode reverseList(ListNode current,ListNode prev){
        if (current.next==null){
            // we have reached the last node. This will be the new head
            current.next = prev;
            return current;
        }
        ListNode head = reverseList(current.next,current);
        current.next=prev;
        return head;
    
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-24
      • 2019-11-07
      • 2012-05-05
      相关资源
      最近更新 更多