LeetCode题解:Remove Duplicates from Sorted List
来源:互联网 发布:nginx 设置默认页面 编辑:程序博客网 时间:2024/06/01 10:43
Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear onlyonce.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->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) { // empty list if (head == nullptr) return nullptr; int current_value; ListNode* fwd_iter = head->next; ListNode* iter = head; current_value = head->val; while(fwd_iter != nullptr) { if (current_value != fwd_iter->val) { if (fwd_iter != iter->next) { ListNode* recycle = iter->next; while(recycle != fwd_iter) { ListNode* tmp = recycle; recycle = recycle->next; delete tmp; }; } iter->next = fwd_iter; iter = fwd_iter; current_value = iter->val; } fwd_iter = fwd_iter->next; } if (iter->next != nullptr) { ListNode* recycle = iter->next; while(recycle != nullptr) { ListNode* tmp = recycle; recycle = recycle->next; delete tmp; } iter->next = nullptr; } return head; }};
- LeetCode题解:Remove Duplicates from Sorted List
- LeetCode题解:Remove Duplicates from Sorted List
- LeetCode题解:Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List ---Leetcode 我的java题解
- LeetCode 题解(160): Remove Duplicates from Sorted List II
- LeetCode 题解(225) : Remove Duplicates from Sorted List
- LeetCode题解-83-Remove Duplicates from Sorted List
- Leetcode题解 83. Remove Duplicates from Sorted List
- LeetCode题解-82-Remove Duplicates from Sorted List II
- leetcode题解-83. Remove Duplicates from Sorted List
- leetcode题解-83. Remove Duplicates from Sorted List
- leetcode题解-82. Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List :from LeetCode
- Leetcode - List - Remove Duplicates from Sorted List
- [leetcode][list] Remove Duplicates from Sorted List
- [leetcode][list] Remove Duplicates from Sorted List
- LeetCode题解:Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array题解
- C++.polymorphism.Simulation of JAVA's DB Interface
- 东九南三之小记
- Camshift算法原理及其Opencv实现
- NSString 截取字符串的某一个部分
- Ubuntu 12.04 文本文件 中文乱码
- LeetCode题解:Remove Duplicates from Sorted List
- delphi文件流
- API函数 CopyFile
- BlockRead和BlockWrite读写文件
- 关于局部变量、全局变量、形式变量和实参变量
- 64位系统下C#解压缩文件
- 在Mac下,快速搭建针对WP8应用的PhoneGap开发环境
- windows server 2012 r2 rtm 激活成功
- linux上svn连接visual svn server时ssl鉴权失败,问题解决