Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->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)
{
return NULL;
}
if(head && head->next == NULL)
{// only one element;
return head;
}
// for two or more;
ListNode * bp = head;
ListNode * ap = head->next;
while(true)
{
while(ap && bp->val == ap->val)
{
ListNode * dp = ap;
if(ap)
{
ap = ap->next;
}
else
{
break;
}
bp->next = ap;
delete(dp);
}
if(!ap)
{
return head;
}
else
{
bp = ap;
ap = ap->next;
}
}
}
};
some hints :
1 = 画图 -> 伪代码 -> real 代码
2 = while true 很好用,可以在任何地方进行break
3 = 多做测试用例; 用测试用例 修改代码 驱动开发。