描述
把链表循环右移k个单位
解决
先算出链表长度,然后把末尾节点指向头节点,然后再从头节点右移length - 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 length = 1;
if (!head)
return NULL;
ListNode *temp = head;
while (head -> next)
{
head = head -> next;
++length;
}
//cout << length << endl;
k %= length;
head -> next = temp;
int zz = length - k;
while (zz && head)
{
head = head -> next;
--zz;
}
temp = head -> next;
head -> next = NULL;
return temp;
}
};