Given a list,rotate the list to right by k places, where k is nonegative.

Given a list,rotate the list to right by k places, where k is nonegative.

给定一个列表,将列表向右旋转K个位置,其中K是非分隔的。

ListNode *rotateRight(ListNode *head, int k) {
	if (head == NULL || k < 0)
		return NULL;

	ListNode* cur = head;
	int count = 0;
	while (cur)
	{
		cur = cur->next;
		count++;
	}

	k = k % count;
	if (k == 0)
		return head;

	ListNode* fast = head;
	ListNode* slow = head;
	while (k--)
	{
		fast = fast->next;
	}

	while (fast->next)
	{

		fast = fast->next;
		slow = slow->next;
	}

	ListNode* newhead = new ListNode(0);
	cur = newhead;
	ListNode* p = slow;
	while (slow->next)
	{
		cur->next = slow->next;
		slow = slow->next;
		cur = cur->next;
	}
	while (head)
	{
		cur->next = head;
		head = head->next;
		cur = cur->next;
		if (head == p)
		{
			head->next = NULL;
		}
	}
	return newhead->next;

}

 

你可能感兴趣的:(Given a list,rotate the list to right by k places, where k is nonegative.)