[LeetCode80]Remove Duplicates from Sorted List II

来源:互联网 发布:centos 7 配置xshell 编辑:程序博客网 时间:2024/06/11 03:29

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.

Analysis

The idea is same with the Question 79 Remove Duplicates from Sorted List.

Difference is there needs a safe head and flag to record whether former is duplicate

java

public ListNode deleteDuplicates(ListNode head) {        if(head == null || head.next == null) return head;        ListNode newHead = new ListNode(-1);        newHead.next = head;        ListNode p1 = newHead;        ListNode p2 = head;        while(p2!=null){        boolean dup = false;        while(p2.next!=null && p2.val == p2.next.val){        dup = true;        p2 = p2.next;        }        if(dup){        p2 = p2.next;        continue;        }        p1.next = p2;        p1 = p1.next;        p2 = p2.next;        }        p1.next = p2;        return newHead.next;    }
c++

ListNode *deleteDuplicates(ListNode *head) {        if(head == NULL || head->next == NULL){            return head;        }        ListNode *p = new ListNode(-1);        p->next = head;        ListNode *cur = p, *pre = head;        while(pre != NULL){            bool isDupli = false;            while(pre->next != NULL && pre->val == pre->next->val){                isDupli = true;                pre = pre->next;            }            if(isDupli){                pre = pre->next;                continue;                         }            cur->next = pre;            cur = cur->next;            pre = pre->next;                    }        cur->next = pre;        return p->next;    }


用JUnit 单元测试

@Testpublic void test() {//new linked listListNode head = new ListNode(1);ListNode l1 = new ListNode(1);ListNode l2 = new ListNode(1);ListNode l3 = new ListNode(2);ListNode l4 = new ListNode(3);//link nodeshead.next = l1;l1.next = l2;l2.next = l3;l3.next = l4;l4.next = null;//pass link list to methodRemoveDuplicateFromSortedList reList = new RemoveDuplicateFromSortedList();reList.deleteDuplicates2(head);}




0 0
原创粉丝点击