# leetcode #61 in cpp

73人阅读 评论(0)

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

}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：7994次
• 积分：1395
• 等级：
• 排名：千里之外
• 原创：139篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行
评论排行