Rotate List
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.
/*************************************************************************
> File Name: LeetCode061.c
> Author: Juntaran
> Mail: [email protected]
> Created Time: Tue 17 May 2016 18:47:57 PM CST
************************************************************************/ /************************************************************************* Rotate List 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. ************************************************************************/ #include <stdio.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k)
{
struct ListNode* fast = head;
struct ListNode* slow = head;
struct ListNode* newhead = head;
int length = ; if( head == NULL || k < )
{
return head;
} while( fast->next != NULL )
{
fast = fast->next;
length ++;
}
fast = head;
k = k % length;
// printf("%d %d\n",k,length); while( k > )
{
fast = fast->next;
if( fast == NULL )
{
return head;
}
k --;
} while( fast->next != NULL )
{
slow = slow->next;
fast = fast->next;
}
fast->next = head;
newhead = slow->next;
slow->next = NULL; return newhead;
}