Java simple solution


  • 1
    D

    The list is sorted. So we only need to compare the current node and the next node.

      public class Solution {
            public ListNode deleteDuplicates(ListNode head) {
                if(head==null||head.next==null)
                    return head;
                ListNode node=head;
                ListNode nextNode=null;
                while(node.next!=null)
                {
                    nextNode=node.next;
                    if(node.val==nextNode.val)
                        node.next=nextNode.next;
                    else
                        node=node.next;
                }
                return head;
            }
        }

  • 0
    P

    Can you explain that why do you return head instead of node in the last line of code?


  • 0
    S
    This post is deleted!

  • 0
    S

    The head pointer always point to the start of linkedList. The node pointer,however, it pointed to the last node of the LinkedList after finishing the while loop.


  • 0
    P

    Thank you. I understand it now.


Log in to reply
 

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