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.
思路一:
定义快慢指针,快指针先走k步,然后快慢指针一起走,最后慢指针走到旋转后的链表的尾部,快指针走到最后一个结点,进行指针的操作,将链表旋转到指定位置即可。
注意:
让快指针走k步前,我们应记录链表的长度n,用k%n才是我们正在要走的长度。
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || k<0)
return NULL;
ListNode* pCur = head;
int n = 0;//记录链表的结点个数
while (pCur)
{
n++;
pCur = pCur->next;
}
k %= n;
ListNode* fast = head;
ListNode* slow = head;
for (int i = 0; i < k; ++i){
if (fast)
fast = fast->next;
}
if (!fast)//k为链表的长度,走到最后了
return head;
while (fast->next)
{
fast = fast->next;
slow = slow->next;
}
//慢指针走到旋转后的链表的尾部,快指针走到最后一个结点
fast->next = head;
fast = slow->next;
slow->next = NULL;
return fast;
}
};
思路二:
也可以将链表的前后指针连接成环,然后走(n-k)%n步,最后断开。
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || k<0)
return NULL;
ListNode* pCur = head;
ListNode* pNext = NULL;
int n = 0;//记录链表的结点个数
while (pCur)
{
n++;
pCur = pCur->next;
}
pCur->next = head;//连接成一个环
int i = (n - k) % n;
while (i--)
{
pCur = pCur->next;
}
//pCur走到旋转后的最后一个节点了
pNext = pCur->next;
pCur->next = NULL;
return pNext;
}
};