[LeetCode] Rotate List
Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example: Given
問題解決の考え方:
この問題の意味はよく分からない.だから何度もNGを出した.
ここでのkは右側のノード数を指し,問題のようにkは4と5を指す.
もう一つの問題は,kがチェーンテーブルの長さより大きい場合にどのように処理すべきかということを理解していない.何度もNGをした結果、k%lenを
これらを理解すれば、コードは簡単です.面接のときは必ず面接官に聞いてください.
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
. 問題解決の考え方:
この問題の意味はよく分からない.だから何度もNGを出した.
ここでのkは右側のノード数を指し,問題のようにkは4と5を指す.
もう一つの問題は,kがチェーンテーブルの長さより大きい場合にどのように処理すべきかということを理解していない.何度もNGをした結果、k%lenを
これらを理解すれば、コードは簡単です.面接のときは必ず面接官に聞いてください.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
int len = getListLen(head);
if(k<=0 || len==0){
return head;
}
k = k%len;
ListNode* myHead = new ListNode(0);
ListNode* tail = myHead;
ListNode* p = head;
for(int i=len-k;i>0;i--){
tail->next = p;
tail=tail->next;
p=p->next;
}
tail->next = NULL;
tail = myHead;
ListNode* q;
while(p!=NULL){
q=p->next;
p->next = tail->next;
tail->next=p;
tail=tail->next;
p=q;
}
head=myHead->next;
delete myHead;
return head;
}
int getListLen(ListNode* head){
int len = 0;
while(head!=NULL){
head=head->next;
len++;
}
return len;
}
};