- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
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 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
/*
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 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
/*
Loop
Unsorted
NULL
1
1 1
1 1 2
1 2 2
1 2 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 == NULL || head->next == NULL) return head;
ListNode* p = head;
ListNode* c = head->next;
ListNode* n = NULL;
bool dup_head = false;
if(head->val == head->next->val)
{
dup_head = true;
c = p;
}
while(c!=NULL)
{
bool flag = false;
while(c->next != NULL && c->val == c->next->val)
{
flag = true;
n = c->next;
delete c;
c = n;
}
if(flag)
{
n = c->next;
delete c;
if(dup_head)
{
head = n;
dup_head = false;
}
else
{
p->next = n;
}
}
c = n;
}
return head;
}
};