您的位置:首页 > 其它

Rotate List问题及解法

2017-07-29 08:34 330 查看
问题描述:

Given a list, rotate the list to the right by k places, where k is non-negative.

示例:

Given 
1->2->3->4->5->NULL
 and k = 
2
,

return 
4->5->1->2->3->NULL
.

问题分析:

根据题意,先求出总的节点个数num,再确定需要旋转后移的个数r = num - k,最后是链表的拼接了。

过程详见代码:

/**
* 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) {
int num = 0;
ListNode* head2 = head;
ListNode* tail;
while (head2)
{
num++;
tail = head2;
head2 = head2->next;
}
if (!num || k % num == 0) return head;
int r = num - k % num;
while (r--)
{
tail->next = head;
head = head->next;
tail->next->next = NULL;
tail = tail->next;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: