[LeetCode]--Remove Duplicate from Sorted List

 这里使用了额外的存储空间,可以使用双指针来实现,不需额外的存储空间.

[LeetCode]--Remove Duplicate from Sorted List
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        
        if(head == null) {
            return null;
        }
        
        HashSet<Integer> s = new HashSet<Integer>();
        
        ListNode pre = null;
        ListNode cur = head;
        
        while(cur != null){
            if(s.contains(cur.val)){
                /*if there‘s a duplicate element, skip the current element*/
                pre.next = cur.next;
                cur = cur.next;
            }else{
                s.add(cur.val);
                pre = cur;
                cur = cur.next;
            }
        }
        
        return head;
        
    }  
}
[LeetCode]--Remove Duplicate from Sorted List

双指针,不使用额外存储空间

[LeetCode]--Remove Duplicate from Sorted List
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        
        if(head == null) return null;
        
        ListNode pre = head;
        ListNode p = head.next;
        
        while(p != null){
            if(pre.val == p.val){
                pre.next = p.next;
                p = p.next;
                continue;
            }
            p = p.next;
            pre = pre.next;
        }
        
        return head;
    }
}
[LeetCode]--Remove Duplicate from Sorted List

[LeetCode]--Remove Duplicate from Sorted List

上一篇:CorelDRAW(CDR)设计绘制现代装饰油画效果之秋色实例教程


下一篇:HAProxy advanced Redis health check---ref