【题目描述】Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
给定一个链表,将链表旋转到右边的k个位置,其中k是非负的。
【解题思路】同之前做过的很多链表题一样,先遍历一遍,为的是得出链表长度length,注意K可能会大于len,因此K%=length。
将尾结点next指针指向首节点,形成一个环,接着往后跑len-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) {
if(head == NULL || head->next == NULL || k <= 0)
return head;
ListNode* pNode = head;
int len = 0;
ListNode* tail;
while(pNode != NULL) {
len++;
if(pNode->next == NULL) tail = pNode;
pNode = pNode->next;
}
tail->next = head;
pNode = tail;
int idx = len - (k % len);
while(idx > 0) {
idx--;
pNode = pNode->next;
}
ListNode* phead = pNode->next;
pNode->next = NULL;
return phead;
}
};