首页 > 其他分享 >82. Remove Duplicates from Sorted List II

82. Remove Duplicates from Sorted List II

时间:2023-03-07 13:05:09浏览次数:43  
标签:head ListNode val Duplicates List Given Remove next return

##题目
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.
##思路
本题采用递归的思路,代码清晰简单
##代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return 0;
        if (!head->next) return head;
        
        int val = head->val;
        ListNode* p = head->next;
        
        if (p->val != val) {
            head->next = deleteDuplicates(p);
            return head;
        } else {
            while (p && p->val == val) p = p->next;
            return deleteDuplicates(p);
        }
    }
};

标签:head,ListNode,val,Duplicates,List,Given,Remove,next,return
From: https://blog.51cto.com/u_15996214/6105914

相关文章

  • 86. Partition List
    ##题目Givenalinkedlistandavaluex,partitionitsuchthatallnodeslessthanxcomebeforenodesgreaterthanorequaltox.Youshouldpreservethe......
  • 442. Find All Duplicates in an Array
    #题目Givenanarrayofintegers,1≤a[i]≤n(n=sizeofarray),someelementsappeartwiceandothersappearonce.Findalltheelementsthatappeartw......
  • ArrayList和LinkedList的区别
    实现接口不同。两个都实现了List接口,LinkedList还实现了Deque接口。底层实现不同。ArrayList是基于数组实现,LinkedList是基于链表实现。效率存在差异。由于底层实现不同......
  • 大白话+画图 从源码角度一步步搞懂ArrayList和LinkedList的使用
    1.说说ArrayList1.基本原理ArrayList,原理就是底层基于数组来实现。01.基本原理:数组的长度是固定的,java里面数组都是定长数组,比如数组大小设置为100,此时你不停的往Arra......
  • CF1787C - Remove the Bracket
    https://codeforces.com/problemset/problem/1787/CThisisthereasonwhytheproblemwasnamedasRemovetheBracket.\begin{aligned}\text{Product}&=a_1\cdo......
  • LinkedList 源码解读
    1.创建 LinkedListList<String>list=newLinkedList<>();list.add("wang");2.构造方法:开起了什么都没有做/***Constructsanemptylist.*/......
  • ArrayList源码解读
    1.创建ArrayListList<String>list=newArrayList<>();list.add("wang");2.构造方法:elementData的长度就是ArrayList的容量,在第一次使用时,elementData的长度会扩展......
  • phthon字符与list常用方法和属性
    字符methods:count:统计字符在字符串中出现的次数(returnint)[searchStr,startIndex,endIndex]mypty='Thisisademoofthecountmethodofstr'print(my......
  • salesforce零基础学习(一百二十六) Picklist Value Set 优缺点和使用探讨
    本篇参考:https://help.salesforce.com/s/articleView?id=sf.fields_creating_global_picklists.htm&type=5当我们创建Picklist字段时,比如很多表很多字段都会用到同样的p......
  • JavaSE——ArrayList集合练习
    packagecom.zhao.test2;publicclassPhone{privateStringlogo;privateIntegerprice;publicPhone(){}publicPhone(Stringlogo,I......