Why input [1,2] exceeds memory limit in my solution? any help is appreciated


  • 0
    S
    import java.util.*;
    public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head ;
        }
        LinkedList<ListNode> q = new LinkedList();
        ListNode n = head;
        while(n!=null) {
            q.push(n);
            n = n.next;
        }
        ListNode h;
        h = q.pop();
        while (!q.isEmpty()) {
            h.next = q.pop();
            h = h.next;
        }
        
        return h;
        
        
    }
    

    }


  • 0
    R

    set the oringinal head.next = None


  • 0
    R

    Otherwise you will get a two node cycle at the end of reversed list


  • 0
    P

    just add one line before the return, h.next = null;


  • 0
    M

    I don't think we should use LinkedList here, instead, we should just use the ListNode implementation in the comment are of this problem.


Log in to reply
 

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