<LeetCode> 题113:删除排序链表中的重复元素2
2016-07-26 14:03
591 查看
1. 题目描述:
给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。例如:
给出 1->2->3->3->4->4->5->null,返回 1->2->5->null
给出 1->1->1->2->3->null,返回 2->3->null
2. 链表数据结构
/** * struct ListNode * { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; **/
3. 代码
3.1 思路1
class Solution { public: ListNode * deleteDuplicates(ListNode *head) { if (head == NULL || head->next == NULL) { return NULL; } ListNode *newhead= new ListNode(0); newhead->next = head; ListNode *pre = newhead; while (pre->next != NULL) { ListNode *cur = pre->next; while (cur->next != NULL && cur->next->val == cur->val) { cur = cur->next; } if (cur != pre->next) { pre->next = cur->next; } else { pre = pre->next; } } return newhead->next; } };
3.2 思路2:
遍历链表,记录相同数字的个数count,如果count=1,则保留,如果count>1,则删除。考虑到重复结点可能在链表表头,所以需要定义一个新的结点,然后连上原链表。class Solution { public: ListNode * deleteDuplicates(ListNode *head) { ListNode *newHead = new ListNode(0); if(head == NULL || head->next == NULL) { return NULL; } ListNode *pre = newHead; ListNode *cur = head; while(head != NULL) { ListNode *p = head; int count = 0;// 记录相同结点的个数 while(p != NULL && p->val == head->val) { p = p->next; count++; } if(count == 1) // count = 1, 说明就只有一个 { pre->next = head; pre = pre->next; head = head->next; } else head = p; } pre->next = NULL;// 断开后面的结点 return newHead->next; } };
相关文章推荐
- Delphi 停靠技术的应用1(在一个窗体中停靠另一个窗体)
- 最长的回文子序列
- post文件的html
- poj 2631 1985 hdoj 2196 <树的直径>
- 8.Hibernate Open Session In View模式
- VBA CurrentRegion属性示例
- 链表基本操作(删除,插入,查找)
- 黑马程序员杭州校区,喜迎PHP 学科入驻
- 高性能Web服务器nginx
- Leach协议在ns2下函数调用视图
- C#中Thread.sleep() 【转载】
- (十六)企业部分之lvs
- JVM性能调优监控工具jps、jstack、jmap、jhat、jstat、hprof使用详解
- mapreduce生命周期的解释及其优化
- iOS 开发者文档翻译 URL Session的生命周期
- linux中的SEM_UNDO
- 设计模式_观察者模式
- mysql 主从原理
- 关于舆情项目的技术点整理(数据库版)
- 如何查看google chrome 插件源码