题目描述
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
样例
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
C 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k){
int n = 0;
if (NULL == head) {
return NULL;
}
struct ListNode* end;
for (struct ListNode* i = head; NULL != i; i = i->next) {
n ++ ;
if (i->next == NULL) {
end = i;
}
}
int start = n - (k % n);
struct ListNode* headNew = head;
for (int i = 1; i < start; i ++ ) {
headNew = headNew->next;
}
end->next = head;
head = headNew->next;
headNew->next = NULL;
return head;
}