What's wrong with my Java solution?


  • 0
    C

    I can't figure out why this doesn't work. It calls "Time Limit Exceeded" on the list [1, 2, 3]:

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

  • 0
    F

    hey,it is obvious that a infinite loop exists in your code, the value of ptr switches from 2 to 1, and never stops.You will see why if u analyze your code step by step.
    Here is my code:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode cur = head;
            while(null != cur){
                ListNode next = cur.next;
                if(cur == head){
                    cur.next = null;
                }else{
                    cur.next = head;
                }
                head = cur;
                cur = next;
            }
            return head;
        }
    }

Log in to reply
 

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