LeetCode题解:Remove Duplicates from Sorted List II
来源:互联网 发布:java开源仓库管理系统 编辑:程序博客网 时间:2024/05/17 11:37
Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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
.
思路:
这次要求只保留出现一次的元素。依然是一次遍历链表,用一个临时链表挂上第一次出现的元素。如果之后发现了重复,就把这个元素去掉,挂上新的元素。这里为了简单,就用了一个vector。
题解:
/** * 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; vector<ListNode*> unique; unique.push_back(head); ListNode* iter = head->next; bool dup = false; while(iter != nullptr) { if (iter->val == unique.back()->val) { dup = true; ListNode* tmp = iter; iter = iter->next; delete tmp; } else { if (dup) { delete unique.back(); unique.pop_back(); } dup = false; unique.push_back(iter); iter = iter->next; } } if (dup) unique.pop_back(); if (unique.empty()) return nullptr; for(int i = 0; i < unique.size() - 1; ++i) unique[i]->next = unique[i + 1]; unique.back()->next = nullptr; return unique.front(); }};
- LeetCode题解:Remove Duplicates from Sorted List II
- LeetCode 题解(160): Remove Duplicates from Sorted List II
- LeetCode题解-82-Remove Duplicates from Sorted List II
- leetcode题解-82. Remove Duplicates from Sorted List II
- LeetCode题解:Remove Duplicates from Sorted List
- LeetCode题解:Remove Duplicates from Sorted List
- 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
- [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
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- pppoe脚本示例
- 【最多约数问题】
- 周记,2013.11.1
- Delphi XE 检查内存泄露
- 博客--start
- LeetCode题解:Remove Duplicates from Sorted List II
- 谷歌浏览器Chrome缓存路径
- LeetCode题解:Simplify Path
- LeetCode题解:Roman to Integer
- 需求分析-关于报表统计类的需求分析
- quickly find the median of a sequence of numbers
- ubuntu 知识点2
- Java Synchronized
- /dev/cdrom: No medium found