Remove Duplicates from Sorted List II ——LeetCode

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.

题目大意:给定一个有序的单链表,删除所有重复元素,只保留出现一次的。

解题思路:记录前驱节点,如果当前元素是重复的,直接把前驱节点的next指向后一个,循环一遍即可。代码写的还是很纠结。WA了五六次。

    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode dummy = new ListNode(0);
        ListNode ptr = head;
        while(head!=null){
            ptr=head;
            while(ptr.next!=null&&ptr.val==ptr.next.val){
                ptr=ptr.next;
            }
            if(head!=ptr){
                head=ptr.next;
            }else{
                break;
            }
        }
        dummy.next=head;
        ListNode tmp = head;
        while(tmp!=null){
            ptr=tmp.next;
            if(ptr==null){
                break;
            }
            while(ptr!=null&&ptr.next!=null&&ptr.val==ptr.next.val){
                ptr=ptr.next;
            }
            if(ptr==tmp.next){
                tmp=tmp.next;
                continue;
            }
            tmp.next=ptr.next;
        }
        return dummy.next;
    }

 

posted @ 2015-06-07 22:35  丶Blank  阅读(146)  评论(0编辑  收藏  举报