[英]java: Memory Limit Exceeded?
我用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;
}
問題是,假設輸入為1-> 2-> 3。 然后,您將返回的是3-> 2-> 1-> 2-> 1-> 2 ....。此循環鏈接列表將在調用toString
方法時導致超出內存限制。 要解決此問題,只需將原始head的下一個設置為null。
這是因為他們希望您以恆定的空間復雜度進行操作。 一個簡單的遞歸解決方案是:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.