当前位置:编程学习 > JAVA >>

Remove Duplicates from Sorted List @LeetCode

 <pre name="code" class="java">/** 
 * Remove Duplicates from Sorted List  
 *  
 * Given a sorted linked list, delete all duplicates such that each element 
 * appear only once. 
 *  
 * For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. 
 */  
public class S83 {  
  
    public static void main(String[] args) {  
        ListNode n1 = new ListNode(1);  
        ListNode n2 = new ListNode(1);  
        n1.next = n2;  
        ListNode n3 = new ListNode(2);  
        n2.next = n3;  
          
        ListNode x = deleteDuplicates(n1);  
        x.print();  
    }  
  
    public static ListNode deleteDuplicates(ListNode head) {  
        ListNode base = head;  // base 为每次被比较的对象  
        if(head==null || head.next == null){  
            return head;  
        }  
        ListNode cur = head.next;       // cur为每次去比较的对象  
          
        while(base!=null && cur!=null){  
            if(base.val == cur.val){        // 重复了就跳过去  
                base.next = cur.next;  
            }else{      // 不重复就更新base  
                base = base.next;  
            }  
            cur = cur.next; // 更新cur  
        }  
          
        return head;  
    }  
}  
</pre><br><br>  
补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,