82. Remove Duplicates from Sorted List II
来源:互联网 发布:淘宝网平板电脑版下载 编辑:程序博客网 时间:2024/06/05 04:56
Description:
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.
解析:使用两个指针head和pass,head不断遍历题目中的链表,遇到不重复的节点便链接到pass后,最后返回pass的头指针即可。这道题我们可以使用迭代和递归两种方法。
迭代版本:
class Solution {public://迭代版 ListNode* deleteDuplicates(ListNode* head) { if(!head || !head->next) return head; ListNode* pass, new_head(0); new_head.next = head; pass = &new_head; while(head && head->next) { if(head->val != head->next->val) { pass->next = head; pass = pass->next; } else { while(head->next && head->val == head->next->val) head = head->next; } head = head->next; } if(head) { pass->next = head; pass = pass->next; } pass->next = NULL; return new_head.next; }};
递归版本:class Solution{public://递归版 ListNode* deleteDuplicates(ListNode* head) { if(!head || !head->next) return head; if(head->val != head->next->val) { head->next = deleteDuplicates(head->next); return head; } while(head->next && head->val == head->next->val) head = head->next; return deleteDuplicates(head->next); } };
阅读全文
0 0
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- SQL 按年,月,日对数据进行分组
- Array.prototype.remove=function(element){}
- Android之在eclipse编译项目出现unable to resolve target android-20解决办法
- 蓝桥杯 算法训练 关联矩阵
- leetcode 153[medium]---Find Minimum in Rotated Sorted Array
- 82. Remove Duplicates from Sorted List II
- BZOJ1143 [CTSC2008]祭祀river 【二分图匹配】
- sshfs
- Failed to sign bin\Debug\app.publish\setup.exe. SignTool Error: No certificates were found that met
- TextView 内容过多,显示不全时,实现带滚动条,上下滑动
- Java8之Optional类(避免空指针异常)
- JS一遍没学会怎么办?
- idea切换eclipse风格后的常用快捷键
- mybatis生成实体类