码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted List II ——LeetCode

时间:2015-06-07 23:31:44      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

 

Remove Duplicates from Sorted List II ——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4559603.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!