- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode * reverseBetween(ListNode * head, int m, int n)
{
if(m>=n) return head;
int cnt_m=m-1;
ListNode * first = head;
ListNode * beffirst = head;
while(cnt_m--) // Skip the first m nodes
{
beffirst = first;
first = first->next;
if(first==NULL) return head;
}
// Reverse nodes in the range
ListNode* c = first->next;
ListNode* p = first;
int k = n-m;
ListNode* nn = NULL;
while(k--)
{
if(c==NULL) return head;
nn = c->next;
c->next = p;
p = c;
c = nn;
}
first->next = c;
if(m!=1) beffirst->next = p;
if(m==1) head = p; // Replace with new head to return.
return head;
}
};