What's wrong with my code? Thanks a lot


  • 0
    D

    Can some one tell me what I have done wrong thanks. this would cause a memory limit exceeded error

    public class Solution {
        public ListNode reverseList(ListNode head) {
            if (head == null) return head;
            
            ListNode next = head.next;
            while (next != null) {
                ListNode temp = next;
                next = next.next;
                temp.next = head;
                head = temp;
            }
            
            return head;
        }
    }
    

  • 0
    D

    never mind. I have figured out. miss a statement. now the correct answer:

    public class Solution {
        public ListNode reverseList(ListNode head) {
            if (head == null) return head;
            
            ListNode next = head.next;
            head.next = null;                                  //this is missing....
            while (next != null) {
                ListNode temp = next;
                next = next.next;
                temp.next = head;
                head = temp;
            }
            
            return head;
        }
    }
    

Log in to reply
 

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