Remove Duplicates from Sorted List II
来源:互联网 发布:工程预算软件有哪些 编辑:程序博客网 时间:2024/06/05 00:46
描述
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.
中文:删除掉所有含有重复元素的结点。
分析:如果此元素与下一个元素是重复的,则删除此元素。
并且记录该元素是否重复。
根据上面的重复标志位,决定最后是否删除该元素。
class Solution {public: ListNode *deleteDuplicates(ListNode *head) { if (head == nullptr) return head; ListNode dummy(INT_MIN); //定义一个头结点 dummy.next = head;//让头结点指向链表第一个节点 ListNode *prev = &dummy, *cur = head;//定义两个指针结点 while (cur != nullptr) { bool duplicated = false; while (cur->next != nullptr && cur->val == cur->next->val) { duplicated = true; ListNode *temp = cur; cur = cur->next; delete temp; } if (duplicated) { // 根据重复位的标志,判断是否删除重复的最后一个元素 ListNode *temp = cur; cur = cur->next; delete temp; continue; } prev->next = cur; prev = prev->next; cur = cur->next; } prev->next = cur; return dummy.next;}};
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
- ASP.NET Web Api 2 接口API文档美化之Swagger
- jsp点击某个按钮回到顶部
- swift数组
- 求白色三角形的最大面积 Triangles
- java中关于this与super那点事
- Remove Duplicates from Sorted List II
- LeetCode236:Lowest Common Ancestor of a Binary Tree
- Ten Ways to Check if an Integer Is a Power Of Two in C
- Guava中Range和Cut简介
- findViewById返回Null
- 2、C语言register关键字—最快的关键字
- HDU 1025 Constructing Roads (最长上升子序列O(n*logn)算法)
- display:none与visible:hidden的区别
- Node.js笔记(九)Nodejs与shell