Leetcode 61 Rotate List
來源:程序員人生 發布時間:2016-12-14 08:26:49 閱讀次數:2450次
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
.
將鏈表右移K位。
先遍歷鏈表知道鏈表的長度,移動的位數會出現大于鏈表長度的情況,所以k=k%cnt
這樣只要在cnt-k處斷開鏈表,把后面的部份放在前臉部分的前面就得到新的鏈表了。
/**
* 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) {
ListNode* p=head;
if(!p) return p;
int cnt=1,cnt2=1;
while(p->next!=NULL)
{
cnt++;
p=p->next;
}
k%=cnt;
if(k==0) return head;
cnt-=k;
ListNode* q=head;
while(cnt2!=cnt)
{
cnt2++;
q=q->next;
}
p->next=head;
head=q->next;
q->next=NULL;
return head;
}
};
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈