Remove Duplicates from Sorted List II(0082/Medium)

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

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.

Given 1->1->1->2->3, return 2->3.

Java代码

public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public ListNode deleteDuplicates(ListNode head) {
       if(head == null || head.next == null)
          return head;

    ListNode dummy = new ListNode(0), p = dummy;
    while(head != null) {
        int val = head.val;
        if (head.next != null && head.next.val == val) {
            //if we have duplicates in pair of values
            head = head.next; //get on last duplicate in pair of values
            while(head != null && head.val == val) 
              head = head.next; // iteratively we get the next value
        }else {
            p.next = head; // head points to unique value
            p = p.next;
            head = head.next;
        }
    }

    //cut off the chain of nodes within original linked list
    p.next = null; 
    return dummy.next;
}

Remove Duplicates from Sorted List (0083/Easy)

题目:

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

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

题解:

这道题是经典的双指针问题,用两个指针一前一后指向链表。如果两个指针指向的值相等,那么就让第二个指针一直往后挪,挪到与第一个指针不同为止。然后让第一个指针的next指向第二个指针,两个指针同时往后挪,进行下面的操作。

需要注意,当list的结尾几个node是重复的时候,例如1->2->3->3,那么ptr2会指向null,需要特殊处理,令ptr1.next = null,这样list尾部就不会丢。

其他情况就不用特殊处理结尾了,因为结尾没有重复值,只须遍历就够了,不用特殊处理尾部

public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)
            return head;

        ListNode ptr1 = head;
        ListNode ptr2 = head.next;

        while(ptr2!=null){
            if(ptr1.val == ptr2.val){
                ptr2 = ptr2.next;
                if(ptr2==null)
                    ptr1.next = null;
            }else{
                ptr1.next = ptr2;
                ptr1 = ptr1.next;
                ptr2 = ptr2.next;
            }
        }

        return head;
    }

results matching ""

    No results matching ""