How to deal with linkedlist? I am bad at it.....cry.....Please help me.


  • 0
    B

    For this problem, I know perhaps the beginning of the list is duplicated,so I know to use dummy nodes. But it tooks me a long time to figure out use pre = dummy and update it only current node's value not equal to next's. I am really worried about it.

    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        if(head==null) return head;
        ListNode pre =dummy;
        ListNode cur = head;
        while(cur!=null && cur.next!=null){
            ListNode next = cur.next;
            if(cur.val!=next.val){pre=cur;cur=next;}
            else{
            while(cur.next!=null && cur.next.val==cur.val)
                cur = cur.next;
            cur = cur.next;
            pre.next = cur;
            }
        }
        return dummy.next;
    }

Log in to reply
 

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