Anyone know why my java code can't pass???? Realy confusing


  • 0
    H
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if (head == null || head.next == null) return head;
            
            ListNode prevNode = new ListNode(0);
            ListNode curNode = head;
            prevNode.next = curNode;
            ListNode nextNode = curNode.next;
            
            while (nextNode != null) {
                if (curNode.val == nextNode.val) {
                    
                    while (nextNode.next != null && nextNode.val == nextNode.next.val) {
                        nextNode = nextNode.next;
                    }
                    
                    if (nextNode.next == null) {
                        curNode = null; // <---------------------I think the problem should come from here
                        return prevNode.next;
                    }
                    else {
                        curNode.val = nextNode.next.val;
                        curNode.next = nextNode.next.next;
                        nextNode = curNode.next;
                    }
                }
                else {
                    curNode = curNode.next;
                    nextNode = nextNode.next;
                }
            }
            return prevNode.next;
        }
    }
    

    when numbers in testing list is always the same like 1-1-1-1, it outputs the 1-1-1-1. Tried in Eclipse, still can't solve it by myself, it seems good on other test lists EXCEPT those ending in same numbers, e.g. 1-2-2-2. Stuck here all day, anyone knows where is the problem? Thanks a lot!!!


  • 0
    M

    u need to free the end of returned list


Log in to reply
 

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