###### leetcode #61 in cpp

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.

Solution:

If k < length of the node, then we use two pointers to find the new head in the list as what we do in #19, and then we delete the link between the new head and its parent, and add link from the tail to the original head.

1->2->3->4, say 3 is the new head

1->2->null 3->4----

|______________|

If k >= length of the node. we rotate k%length. It is simply like rotating a circle.

Code:

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {

int len = 0;

while(cur){//calculate how long the linked list is
len++;
cur = cur->next;
}

k %=len;

len =0;
while(len<k && cur->next){//separate cur k distance from prev
cur = cur->next;
len++;
}
while(cur->next){//move cur to tail. prev->next is the beginning of the section we are to rotate
cur = cur->next;
prev = prev->next;
}
prev->next = NULL;//put prev as tail

}
};

#### leetCode练习（61）

2016-10-11 16:57:52

#### LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

#### [leetcode-61]Rotate List(c)

2015-08-04 09:04:28

#### 免费的LeetCode-cpp题解(C++版本)大全 pdf下载

2018年01月18日 807KB 下载

#### (Java)LeetCode-61. Rotate List

2016-10-06 17:52:28

#### LeetCode 61 — Rotate List（C++ Java Python）

2014-02-24 22:11:31

2016-07-21 09:37:42

#### LeetCode347—Top K Frequent Elements

2016-05-03 16:20:00

#### LeetCode OJ 之 Palindrome Linked List（回文链表判断）

2015-07-14 14:16:40

#### Leetcode 283. Move Zeroes (Easy) (cpp)

2016-07-12 11:59:39

## 不良信息举报

leetcode #61 in cpp