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

【Leetcode】83. Remove Duplicates from Sorted List

时间:2018-02-25 13:11:44      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:div   linked   example   dup   body   return   tno   rem   bre   

Question:

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

Tips:将一个有序链表中的重复val的结点删除。

思路:

设置一个指针,当指针下一个结点的val值与当前指针val相等就指针指向下一个结点的下一个。

cur.next=cur.next.next;

代码:

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

递归:

public ListNode deleteDuplicates2(ListNode head) {
        if (head == null || head.next == null)
            return head;
        head.next  =deleteDuplicates2(head.next);
        return head.val==head.next.val?head.next:head;
    }

 

【Leetcode】83. Remove Duplicates from Sorted List

标签:div   linked   example   dup   body   return   tno   rem   bre   

原文地址:https://www.cnblogs.com/yumiaomiao/p/8468738.html

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