具体思路就是先遍历链表求出长度,然后对k取余。通过3个指针实现旋转链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k) {
if(head == NULL || head->next == NULL || k == 0)
return head;
int len = 0;
struct ListNode *current = head,*pre = head,*next = head; // 其实不是next而是pre 随便取了个名字
while(current){
next = current;
// len++;
current = current->next;
len++;
}
k = k % len;
if(k == 0)
return head;
current = head;
for (int i=0;i<len - k;i++){
pre = current;
current = current->next;
}
pre->next = NULL;
next->next = head;
return current;
}