輪換名單Leetcode解決方案

`head = [1,2,3,4,5], k = 2`
`[4,5,1,2,3]`

`head = [0,1,2], k = 4`
`[2, 0, 1]`

旋轉列表Leetcode解決方案的代碼

C ++代碼

```#include <bits/stdc++.h>
using namespace std;

struct ListNode{
int data;
ListNode* next;
};

ListNode* rotateRight(ListNode* head, int k) {
if(head==NULL || head->next==NULL)return head;

ListNode *tmp = head;
int cnt = 0;
while(tmp)tmp=tmp->next,cnt++;
tmp=head;
k%=cnt;
if(k==0)return head;

while(k--)tmp = tmp->next;
ListNode *tmpHead = head;
while(tmp->next!=NULL){
tmp = tmp->next;
head = head->next;
}
ListNode* newHead = head->next;
tmp->next = tmpHead;
head->next = NULL;
return newHead;
}

int main(){
ListNode *head = new ListNode();
head->data = 0;
head->next = new ListNode();
head->next->data = 1;
head->next->next = new ListNode();
head->next->next->data = 2;

head = rotateRight(head, 4);
while(head != NULL){
cout<<head->data<<" ";
head = head->next;
}
}
```
`2 0 1`

Java代碼

```import java.util.*;
import java.lang.*;
import java.io.*;

class ListNode{
int data;
ListNode next;
}

class Solution {
public static ListNode rotateRight(ListNode head, int k) {
if(head==null || head.next==null)return head;

ListNode tmp = head;
int cnt = 0;
while(tmp != null){
tmp=tmp.next;
cnt++;
}
tmp=head;
k %= cnt;
if(k==0)return head;

while(k-- > 0)
tmp = tmp.next;
ListNode tmpHead = head;
while(tmp.next != null){
tmp = tmp.next;
head = head.next;
}
ListNode newHead = head.next;
tmp.next = tmpHead;
head.next = null;
return newHead;
}

public static void main(String[] args){
ListNode head = new ListNode();
head.data = 0;
head.next = new ListNode();
head.next.data = 1;
head.next.next = new ListNode();
head.next.next.data = 2;

head = rotateRight(head, 4);
while(head != null){
System.out.print(head.data + " ");
head = head.next;
}
}
}```
`2 0 1`

複雜度分析

空間複雜度

O（1）， 因為我們不需要為每個節點存儲信息。 因此，空間複雜度是恆定的。