首页 > 其他 > 详细

[leetcode]82. Remove Duplicates from Sorted List

时间:2018-02-11 14:12:44      阅读:174      评论:0      收藏:0      [点我收藏+]

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

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

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

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