No.206 code cause MLE. WHY?


  • 0
    C

    public class Solution {

    public ListNode reverseList(ListNode head) {
        Stack<ListNode> stck=new Stack<ListNode>();
        ListNode result=null;
        if (head==null){
        	return result;
        }
        else{      	
        	
        	while (head.next !=null){
        		stck.push(head);
        		head=head.next;
        	}
        	result =head;
        	if(!stck.empty()){  
        		head.next=stck.pop();
        		head=head.next;
        	}
        	
        }
        return result;  
    }
    

    }


  • 0
    N

    You don't need to create a Stack in this code. The Stack use at least the same amount of memory as the original linked list.You should be able to make it in-place.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.