问题描述:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
解题笔记:
(1) 第一次Submit
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode* pK = head;
ListNode* pCur = head;
ListNode* pLast = NULL;
ListNode* pKLast = NULL;
int curlength = 0;
while (pCur)
{
if (pCur->next==NULL)
{
pLast = pCur;
}
pCur = pCur->next;
if (curlength==k)
{
pKLast = pK;
pK = pK->next;
}
else //curlength<k
{
curlength += 1;
}
}
pLast->next = head;
pKLast->next = NULL;
return pK;
}
};
觉得此题挺简单的,写完没多想就提交,直接Runtime Error,上面的代码看上去逻辑挺清晰的,但是实际上好多边界条件没有处理好。
(2) 第二次Submit
修改了一下:
1 class Solution { 2 public: 3 ListNode* rotateRight(ListNode* head, int k) { 4 if (head==NULL || k==0) 5 { 6 return head; 7 } 8 9 ListNode* pK = head; 10 ListNode* pCur = head; 11 ListNode* pLast = head; 12 ListNode* pKLast = NULL; 13 14 int curlength = 0; 15 int listLength = 0; 16 while (pCur) 17 { 18 if (pCur->next==NULL) 19 { 20 pLast = pCur; 21 } 22 pCur = pCur->next; 23 listLength += 1; 24 25 if (curlength==k) 26 { 27 pKLast = pK; 28 pK = pK->next; 29 } 30 else //curlength<k 31 { 32 curlength += 1; 33 } 34 35 } 36 37 if (listLength<=k) 38 { 39 return head; 40 } 41 42 pLast->next = head; 43 pKLast->next = NULL; 44 return pK; 45 } 46 };
蛮有信心的提交,结果:
Wrong Answer
Input:{1,2}, 3
Output:{1,2}
Expected:{2,1}
崩溃。为啥呀?看来题目理解有问题了,啥叫做rotate the list to the right by k places?
#¥@……%&!@……#
无奈只好看了Discuss,好吧,应该是这样理解的。看了discuss一哥们的思路,不错,把链表头尾接起来,这样最多循环遍历不到两次,就可以完成。
如下是俺看了思路以后编写的代码:
1 class Solution { 2 public: 3 ListNode* rotateRight(ListNode* head, int k) { 4 if (head==NULL || head->next==NULL || k==0) 5 { 6 return head; 7 } 8 9 ListNode* pTail = head; 10 int listLength = 1; 11 while (pTail->next) 12 { 13 pTail = pTail->next; 14 listLength += 1; 15 } 16 k = k % listLength; 17 int bk = listLength - k; 18 19 pTail->next = head; 20 21 for (int i = 0; i < bk; ++i) 22 { 23 pTail = pTail->next; 24 } 25 head = pTail->next; 26 pTail->next = NULL; 27 28 return head; 29 } 30 };
此法代码果然简洁啊!惭愧。