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

[leetcode]82. Remove Duplicates from Sorted List

时间:2018-02-11 14:46:43      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:duplicate   遍历   nod   color   next   重复节点   sorted   move   class   

第一题:遍历链表,遇到重复节点就连接到下一个。

public ListNode deleteDuplicates(ListNode head) {
        if (head==null||head.next==null) return head;
        ListNode res = head;
        while (head.next!=null){
            if (head.val==head.next.val)
            {
                if (head.next.next!=null) head.next = head.next.next;
                else head.next = null;
            }
            else head = head.next;
        }
        return res;
    }

 

第二题:思路比较简单,设置一个超前节点作为head的前节点,往下遍历,遇到重复的就把超前节点连接到新的val节点。

public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode res = new ListNode(0);
        res.next = head;
        ListNode list = res;
        while (res.next!=null&&res.next.next!=null)
        {
            ListNode temp = res.next.next;
            if (res.next.val==res.next.next.val)
            {
                while (temp.next!=null&&temp.next.val==temp.val)
                {
                    temp = temp.next;
                }
                if (temp.next!=null) res.next = temp.next;
                else res.next = null;
            }
            else res =res.next;
        }
        return list.next;
    }

 当要经常删除第一个节点是,要设置一个超前节点

[leetcode]82. Remove Duplicates from Sorted List

标签:duplicate   遍历   nod   color   next   重复节点   sorted   move   class   

原文地址:https://www.cnblogs.com/stAr-1/p/8441120.html

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