刪除排序鏈表中的重複元素

給定一個排序鏈表,刪除全部重複的元素使得每一個元素只留下一個。code

案例:排序

給定 1->1->2,返回 1->2List

給定 1->1->2->3->3,返回 1->2->3鏈表

public ListNode deleteDuplicates(ListNode head){
        if (head==null||head.next==null){
            return head;
        }
        ListNode pre = head;
        ListNode next = head.next;
        while (next!=null){
            if (pre.val==next.val){
                pre.next=next.next;
            }
            else {
                pre = next;
            }
            next=next.next;
        }
        return head;
    }
相關文章
相關標籤/搜索