2014年9月30日星期二

[Leetcode] 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,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
稍微复杂一点的链表题,牢牢记住,只要涉及删除并且是单链表的,就需要记录可能删除的节点的之前的节点,所以使用三个指针,其中两个用来扫描,另外一个表示目前目前的合法的链表的结尾。尤其注意空指针的情况!需要对两个用来扫描的指针进行判断以免出现空指针的错误。
public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode temp = dummy, temp1 = head, temp2 = head.next;
        
        while(temp2 != null) {
            if(temp1.val == temp2.val) {
                while(temp2 != null && temp2.val == temp1.val) temp2 = temp2.next;
                temp.next = temp2;
                temp1 = temp2;
                if(temp2 != null) temp2 = temp2.next;
            }
            else {
                temp = temp1;
                temp1 = temp2;
                temp2 = temp2.next;
            }
        }
        
        return dummy.next;
    }

没有评论:

发表评论