题目描述:
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2 输出: 4->5->1->2->3->NULL 解释: 向右旋转 1 步: 5->1->2->3->4->NULL 向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4 输出:2->0->1->NULL
解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步:0->1->2->NULL
向右旋转 4 步:2->0->1->NULL
解题思路:正常使用快慢指针解出即可,本次着重介绍一个简便算法,我们可以将链表前后连起来,假设链表长为n,旋转k步也就是说旋转到了n-k%n+1的位置,所以我们将链表连起来后,旋转到n-k%n的位置时,断开链表即可。
代码实现:
/**
* 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) {
if(k==0||!head) return head;
int n=1;
ListNode *temp=head;
ListNode *p;
while(temp->next){ //计算出链表的长度
n++;
temp=temp->next;
}
temp->next=head; //将链表手尾相连
int m=n-k%n;
for(int i=0;i<m;i++){
temp=temp->next;
}
p=temp->next; //再断开链表
temp->next=NULL;
return p;
}
};