# 61. Rotate List

## 1.問題

* 給予一個list, 讓list旋轉k格

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LNbfaAKz0WhJWb-rltV%2F-LNbscmnEsc1uv3QUOj2%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-30%20%E4%B8%8A%E5%8D%888.30.30.png?alt=media\&token=22d8109a-d8f5-40c8-a4cf-c28030806fe2)

## 2.想法

* 提問
* parameter
* test input
* 觀察
  * 旋轉後將會讓第(n - k)個node為新的head
* 說明想法&#x20;
  * 先create新的ptr並移動到尾部, 讓list的尾部接到頭部, 形成cycle, 移動last向前 (n - k), 新的head即為last->next, 並讓last->next = NULL
* 測試計算複雜度

## 3.程式碼

```
/**
 * 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) {
        while (!head) {
            return head;
        }
        
        int index = 0, cnt = 1;
        ListNode* last = head, *newHead = 0;
        while (last->next) {
            last = last->next;
            cnt++;
        }
        last->next = head;

        k = (k % cnt);
        
        for (int i = 0 ; i < (cnt - k); i++) {
            last = last->next;
        }
        newHead = last->next;
        last->next = NULL;
        
        return newHead;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/61.-rotate-list.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
