Remove Duplicates from Sorted List II
来源:互联网 发布:人工智能会毁灭人类 编辑:程序博客网 时间:2024/05/20 13:06
一、问题描述
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 NULL; if(!head -> next) return head; ListNode* p = head -> next; int data = head -> val; if(p -> val != data){ head -> next = deleteDuplicates(p); return head; }else{ while(p && p -> val == data) p = p -> next; return deleteDuplicates(p); } }};
0 0
- LeetCode: Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove duplicates from sorted list II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- Spark学习之Scala和idea工具安装
- ulua里如何将C#创建的UnityEngine对象返回给lua
- python整型
- RxJava的使用,教你四步搞定RxBus.
- 自定义present动画的屏幕变黑的一个坑
- Remove Duplicates from Sorted List II
- Android基础———ViewPager
- java解题公共汽车
- 运维日记011 - Ubuntu下更改初始用户名的方法
- Github 使用方法
- HTML基础样式(二)
- Vector与ArrayList区别
- leetcode---Water and Jug Problem
- JavaScript调试之console命令的各函数用法