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.

解题方法

  1. 使用Dummy node 保留開頭
  2. 確認head.next != null && head.nexnt.next != null
    public ListNode deleteDuplicates(ListNode head){
        //corner case
        if(head == null || head.next == null){  //0 or 1 node only
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        while(head.next != null && head.next.next != null){
            if(head.next.val == head.next.next.val){
                head.next = head.next.next;
            }else{
                head = head.next;
            }
        }

        return dummy.next;
    }

82. Remove Duplicates from Sorted List II

题目描述

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

解题方法

  1. 使用Dummy node 保留開頭
  2. 確認head.next != null && head.nexnt.next != null
  3. 因為duplicate elements 都必須刪除,所以用int紀錄並全數移除
    public ListNode deleteDuplicates(ListNode head){
        //corner case
        if(head == null || head.next == null){
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        while(head.next != null && head.next.next != null){
            if(head.next.val == head.next.next.val){
                int val = head.next.val;
                while(head.next != null && head.next.val == val){
                    head.next = head.next.next;
                }
            }else{
                head = head.next;
            }
        }
        return dummy.next;
    }

results matching ""

    No results matching ""