Leetcode83. Remove Duplicates from Sorted List

Posted 于淼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode83. Remove Duplicates from Sorted List相关的知识,希望对你有一定的参考价值。

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

 



以上是关于Leetcode83. Remove Duplicates from Sorted List的主要内容,如果未能解决你的问题,请参考以下文章

leetcode83-Remove Duplicates from Sorted List

[LeetCode] 83. Remove Duplicates from Sorted List

LeetCode83 Remove Duplicates from Sorted List

LeetCode 83 Remove Duplicates from Sorted List

LeetCode:83.Remove Duplicates from Sorted List

leetcode83 Remove Duplicates from Sorted List