83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

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

你可能感兴趣的:(83. Remove Duplicates from Sorted List)