Remove Duplicates from Sorted List

Remove Duplicates from Sorted List
 1 public class Solution {
 2 
 3     public ListNode deleteDuplicates(ListNode head) {
 4         if(head==null)
 5         return null;
 6         if(head.next==null){
 7             return head;
 8         }
 9         ListNode p1=head;
10         ListNode p2=head.next;
11         while(p2!=null){
12             if(p1.val==p2.val){
13                 while(p2!=null&&p1.val==p2.val){
14                     p2=p2.next;
15                 }
16                 
17                 p1.next=p2;
18                 p1=p2;
19                 if(p2!=null){
20                     p2=p2.next;
21                 }
22             }
23             else{
24                 p1=p1.next;
25                 p2=p2.next;
26             }
27         }
28         return head;
29     }
30 }
View Code

Given a sorted linked list, delete all duplicates such that each element appear only once.

Remove Duplicates from Sorted List

上一篇:Minimum Depth of Binary Tree


下一篇:Maximum Depth of Binary Tree