leetcode:單鏈表之Rotate List
題目:
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->nullptr and k = 2, return 4->5->1->2->3->nullptr.
即:給出一個單鏈表,和一個K值,根據K值往右旋轉。
分析:這裏的k可能是比鏈表長度要大的數字,因此實際旋轉的位置通過k= len - k % len來獲得;
輸入;
當k=1時,旋轉後結果:
當k=2時,旋轉後結果:
當k=3時,旋轉後結果:
當k=4時,旋轉後結果:
當k=5時,旋轉後結果:
當k=6時,旋轉後結果:
...
c++實現:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode (int x):val(x),next(NULL){ }
};
ListNode *createListNode(int arr[],int n)
{
ListNode *r;
ListNode *p;
ListNode * L=(ListNode*)malloc(sizeof(ListNode));
r=L;
for(int i=0;i<n;i++)
{
p=(ListNode*)malloc(sizeof(ListNode));
p->val=arr[i];
r->next=p;
r=p;
}
r->next=NULL;
return L->next;
}
ListNode *rotateRight(ListNode *head, int k)
{
if (head == NULL || k == 0)
return head;
int len = 1;
ListNode* p = head;
while (p->next) // 求長度
{
len++;
p = p->next;
}
k= len - k % len;
p->next = head; // 首尾相連
for(int step = 0; step < k; step++)
{
p = p->next; //接着往後跑
}
head = p->next; // 新的首節點
p->next = NULL; // 斷開環
return head;
}
int main()
{
int a[]={1,2,3,4,5};
ListNode *input;
ListNode *out;
int k=2;
input= createListNode(a,5);
out=rotateRight(input, k);
while(out != NULL)
{
cout<<out->val;
out = out->next;
}
cout<<endl;
return 0;
}
測試結果: