LeetCode(82)题解: Remove Duplicates from Sorted List II
2015-08-08 16:23
477 查看
https://leetcode.com/problems/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
Given
思路:
需要两个指针,a用来纪录新链表,b用来遍历老链表,因为只有删除操作,需要一个flag标记ab段要不要删除。此外要注意头节点的处理。
AC代码:
题目:
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.
思路:
需要两个指针,a用来纪录新链表,b用来遍历老链表,因为只有删除操作,需要一个flag标记ab段要不要删除。此外要注意头节点的处理。
AC代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head==NULL) return NULL; ListNode* newhead=new ListNode(0); // to handle head newhead->next=head; ListNode* a=newhead,*b=newhead->next; int now=head->val; bool occur_flag=false; while(b->next!=NULL){ if(b->next->val==now){ occur_flag=true; } else{ if(occur_flag==true){ a->next=b->next; //delete duplicate numbers b=a; //update pointers } else{ a=b; } occur_flag=false; now=b->next->val; } b=b->next; } if(occur_flag==true){ a->next=b->next; //delete duplicate numbers b=a; //update pointers } else{ a=b; } return newhead->next; } };
相关文章推荐
- Android性能优化典范
- android服务的总结
- HDU 2473 Junk-Mail Filter(删点)
- git基本操作
- HDU 4745 Two Rabbits(区间DP)
- POJ 3278 Catch that cow
- hdu 1253 胜利大逃亡
- 干净清爽界面---资源浏览器形式的TXT阅读软件
- UVA 1423 Guess 【拓扑排序】
- Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart
- 自学perl 系列1
- 二分回顾
- 【Obective-C编程开发】Objective-C之BOOL一清二楚
- C语言中关于.h文件和.c文件详细解析
- C.Stripe(Codeforces Beta Round #18 (Div. 2 Only))
- 用户'sa'登录失败(DataGridView)
- MySQL连接查询
- 部分华为校园招聘机试试题及答案(C语言版本)
- 文件描述符及其重定向的学习笔记
- Input设备驱动之事件类型