首页 > 其他 > 详细

Remove Duplicates from Sorted List II

时间:2014-02-23 07:09:00      阅读:283      评论: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.

基本思路:

这个题目较上一个题的不同之处在于,本题中要删除重复元素,采用的思路是先找到head指针,就是头指针,例如:1->1->1->2->3 头指针就是指向2的指针,1->2->3->3->4->4->5头指针就是指向1的指针,以此类推,然后从

指针开始扫描,类似上一题。

    public ListNode deleteDuplicates(ListNode head) {
        if(head==null)
            return null;
        ListNode p = head,pre;
        ListNode nextNode = p.next;
        boolean hasFound = false;
        int temp = 0;
        int flag = 0;
        if(nextNode==null)
            return head;
        while(nextNode!=null)
        {
            if(p.val!=nextNode.val&&flag==0)
            {
                head = p;
                hasFound = true;
                break;
            }
            else if(p.val!=nextNode.val&&flag==1)
                flag = 0;
            else if(p.val==nextNode.val)
                flag = 1;
            p = nextNode;
            nextNode = p.next;
        }
        if(hasFound==false)
        {
            if(p!=null&&flag==0)
                head = p;
            else
                return null;
        }
        p = head.next;
        pre = head;
        if(p!=null)
            temp = pre.val;
        while(p!=null)
        {
            if(temp!=p.val)
            {
                if(p.next!=null&&p.next.val!=p.val)
                {
                     pre.next = p;
                     pre = p;
                }
                if(p.next==null)
                    pre.next = p;
                temp = p.val;
                flag = 0;
            }
            else
            {
                flag = 1;
            }
            p = p.next;
        }
        if(flag==1)
            pre.next = null;
        return head;
    }



Remove Duplicates from Sorted List II

原文:http://blog.csdn.net/cow__sky/article/details/19689335

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!