Remove Duplicates from Sorted List II

来源:互联网 发布:ibn软件 编辑:程序博客网 时间:2024/05/03 09:56

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.

check the coding in detail below

 /*    Key to Solve: archive time in O(n)    1.use Dummy  + dummyTemp nodes    2.create nodes of curr and nextNode points    3.solve problem base on duplication and non-duplication case     */    public static ListNode deleteDuplicates(ListNode head) {        //check for corner case        if(head==null || head.next==null) return head;        ListNode dummy=new ListNode(0);        dummy.next=head;        ListNode dummyTemp=dummy;        ListNode curr=head;        ListNode nextNode=head.next;        while(nextNode!=null){            if(curr.val!=nextNode.val){                //no duplication was found                if(curr.next==nextNode){                    dummyTemp=curr;                }else{ //Duplication was found, then skip it                    dummyTemp.next=nextNode;                }                //In order to skip duplication, move curr to position of nextNode                curr=nextNode;            }            nextNode=nextNode.next;        }        if(curr.next!=null){            dummyTemp.next=null;        }        return dummy.next;    }


0 0
原创粉丝点击