leetcode 82:Remove Duplicates from Sorted List II
2015-11-30 20:49
351 查看
题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
思路:
/**
* 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||!head->next)return head;
ListNode *newhead=0,**phead=&newhead;//phead pointer to new head pointer
while(head)
{
if(head->next&&head->val==head->next->val)
{//skip all nodes has duplicate value
int dupval=head->val;
while(head&&head->val==dupval)head=head->next;
continue;
}//assign and advance phead
else {*phead=head; phead=&((*phead)->next);}
head=head->next;
}
*phead=0;// point the next of last node to NULL
return newhead;
}
};
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.
思路:
/**
* 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||!head->next)return head;
ListNode *newhead=0,**phead=&newhead;//phead pointer to new head pointer
while(head)
{
if(head->next&&head->val==head->next->val)
{//skip all nodes has duplicate value
int dupval=head->val;
while(head&&head->val==dupval)head=head->next;
continue;
}//assign and advance phead
else {*phead=head; phead=&((*phead)->next);}
head=head->next;
}
*phead=0;// point the next of last node to NULL
return newhead;
}
};
相关文章推荐
- hdoj5563Clarke and five-pointed star【判断五角星】
- 【转】获取URL中的 参数
- 一个简单的溢出程序解析
- BZOJ 1011: [HNOI2008]遥远的行星( )
- mac重装系统
- 走过电竞之路的程序员
- iOS笔记19
- 首次适应算法和最佳适应算法和循环首次适应算法和最坏适应算法
- 走过电竞之路的程序员
- 走过电竞之路的程序员
- centos下mysql主从搭建总结
- react 入门知识
- 【学习总结】【多线程】 线程 & 进程 & NSThread(多线程的一套API)
- 网页设计易错点总结
- cocos2dx之SpriteBatchNode的作用
- hpuoj 1718: 感恩节KK专场——KK和女票一起遛狗 (水题)
- 人类的行为与程序计算
- ASCII学习对照表
- python IOError: cannot identify image file
- 自己实现的简单heap max_heap和min_heap 还有sort