- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
Remove Duplicates from Sorted List
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==NULL || head->next==NULL) return head;
ListNode* c = head->next;
ListNode* p = head;
while(c!=NULL) // We assume that there is no loop in the list.
{
ListNode* n = c->next;
if(p->val == c->val)
{
p->next = n;
delete c;
c = n;
}
else
{
p = c;
c = n;
}
}
return head;
}
};