LeetCode 82. Remove Duplicates from Sorted List II pre指针,首元素的处理
来源:互联网 发布:tfboys三只的关系知乎 编辑:程序博客网 时间:2024/06/27 03:09
- 题目
- 题意
- 注意
- 思路
- 代码
- 结果
- 题目
题目
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.
题意
给定一个有序的链表,删除所有重复结点,仅仅留下出现过一次的结点
注意
- 根据题意知道,是删除所有的重复的结点
- 作为重复元素中第一个元素应该如何处理
- 和82. Remove Duplicates from Sorted List 203. Remove Linked List Elements的区别。
思路
1.设置三个指针pre,cur,next。pre指向cur前一个元素,next往后一位查找和cur的值是否相等,当没有相等时,pre移动到cur的位置,cur往前走一步。
2.当next往后一位找到和cur有相等的,就删除next指向的结点,并继续往后一位看和cur是否相等,相等继续删除,不等退出循环。在这个过程中需要维护好cur->next和next->next的信息。
3.继续第二步骤,当cur之后和它相等的已经删除完毕退出循环,说明cur本身是重复元素的起始元素,继续对cur进行删除,cur指向下一个不重复元素。
代码
class Solution {public: ListNode* deleteDuplicates(ListNode* head) { ListNode *virtualNode = new ListNode(0); virtualNode->next = head; ListNode* cur = virtualNode->next; //这就是虚拟结点的存在的理由,从虚拟结点处当做当前结点 //判断的是当前结点的下一结点 ListNode* pre = virtualNode; while (cur != NULL) { ListNode* next = cur->next; bool flag = false; //用来处理重复元素的第一位元素 while (next != NULL) { if (cur->val == next->val) { ListNode* dele = next; //cur和next处理的结果不可以一致 cur->next = next->next; //cur = cur->next; next = next->next; delete dele; flag = true; } else { break; } } if (flag) { ListNode* firstdele = cur; //有重复元素,一定要在这里处理cur,否则马上执行删除操作 cur = cur->next; delete firstdele; pre->next = cur; continue; } else { //当没有重复元素的时候,pre指向当前的cur的结点 //而cur马上需要更新到下一结点 pre = cur; } cur = cur->next; } ListNode* retNode = virtualNode->next; delete virtualNode; return retNode; }};
结果
阅读全文
0 0
- LeetCode 82. Remove Duplicates from Sorted List II pre指针,首元素的处理
- 【Leetcode】82 Remove Duplicates from Sorted List II 【指针&链表】
- Leetcode-Remove Duplicates from Sorted List II(二级指针)
- leetcode 82-- Remove Duplicates from Sorted List II 链表 双指针 删除元素
- Leetcode Remove Duplicates from Sorted List II 删除链表中重复的元素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
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- OkHttp的简单使用
- (一)Kafka中文教程-初识kafka
- Shader的介绍
- 【解决】linux下svn权限配置不起作用
- java基础提高篇--类型转换
- LeetCode 82. Remove Duplicates from Sorted List II pre指针,首元素的处理
- [笔记]: 树状数组
- [iOS] objc_setAssociatedObject objc_getAssociatedObject 简单明了的一个理解
- JVM加载class文件的原理机制
- 《Android源码设计模式解析与实战》读书笔记(十五)——模板方法模式
- Java类加载器介绍总结
- 实际项目中常用的加密算法及使用场景
- jsp页面的中循环获取数据
- Linux 删除文件夹和文件的命令(强制删除包括非空文件)