leetcode 虐我篇之(四)Remove Duplicates from Sorted List II
来源:互联网 发布:沈阳直销软件 编辑:程序博客网 时间:2024/06/06 14:16
前面做了Remove Duplicates from Sorted List 今天就顺便把Remove Duplicates from Sorted List II 也做一下。前面的第一个去重的可以参考我的前一篇文章。
题目的描述如下:
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.题目也是讲得比较直白了。程序可以将上一篇的文章的代码改一下就好。但是就在这个改一下的过程中,我遇到了很多问题。总是没有很好的把结果正确输出。一开始我是加了有重复的标志位eq,然后又加了指针pre,写着写着感觉如果一开始就遇到重复的怎么办?然后就加了其它一堆判断条件和标志位,退出循环后,为了避免漏判断又加了一堆判断条件和标志位。在网站上提交了好几次,每次都会有问题。改来改去,好烦啊。正所谓浅水淹死大牛,何况我这种笨猪。后面搞了好久好久好久好久,终于想到怎么将判断条件加上去。后面提交的时候,看着pending的时候好紧张,结果出来Accepted的时候终于舒了口气。
代码如下:
ListNode *deleteDuplicates2(ListNode *head){if (!head){return NULL;}ListNode *pt = head;ListNode *pre = head;bool eq = false;//遍历链表while(pt!= NULL && pt->next){if (pt->val == pt->next->val){pt->next = pt->next->next;eq = true;}else{//如果前一次是有相同的情况if (eq){//如果前一个指针和头结点指针相等的情况if (pre == head && pre == pt){head = pt->next;pre = head;pt = pre;}else{pre->next = pt->next;pt = pre->next;}eq = false;}else{pre = pt;pt = pre->next;}}}//这里的判断是必须的,为了防止最后两个是相等的情况。if (eq){if (pre == head && pre == pt){head = pt->next;pre = head;}else{pre->next = pt->next;}}return head;}代码中的注释比较少,但是代码还是比较清楚简单的。
看了一下时间,快十一点了。宿舍要关门了。就写到这里。唉,今晚被虐惨了!
0 0
- leetcode 虐我篇之(四)Remove Duplicates from Sorted List II
- leetcode 虐我篇之(六)Remove Duplicates from Sorted Array II
- leetcode 虐我篇之(三)Remove Duplicates from Sorted List
- leetcode系列(66)Remove Duplicates from Sorted List,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
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 浅析UML之组件图
- LeetCode-Single Number II
- 用ORACHK自动化检查数据库系统的健壮性
- sql必知必会读书笔记二
- hdu 4891The Great Pan -----------2014 Multi-University Training Contest 3
- leetcode 虐我篇之(四)Remove Duplicates from Sorted List II
- 为什么呢????没有封号啊
- Prevent the user click a button twice
- 浅析UML之组织结构图
- android项目解刨之时间轴
- 队列的实现
- cocos2d-x-3.2版本win7环境中的搭建
- ReportStudio入门教程(七十五) - 计算项的运算顺序
- 修改登陆密码