思路:
1、判断链表节点数
struct ListNode* rotateRight(struct ListNode* head, int k){
//如果链表最多只有1个节点,则返回头节点
if(head == NULL || head -> next == NULL) {
return head;
}
2、定义指针
//定义指针
struct ListNode* node = head;
struct ListNode* node1 = head;
struct ListNode* slow = head;
struct ListNode* fast = slow -> next;
3、遍历链表找出节点数后判断,便于后续运行节省时间
//先遍历链表数出节点数i,若所给的k是i的整数倍,则旋转后的链表与原链表相同
int n=0,i=0;
while(node1) {
node1 = node1 -> next;
i++;
}
if(k % i == 0) {
return head;
} else {
k = k % i;//若k不是i的整数倍,则取余,可以减少所用时间
}
4、将fast和slow指针一起走,fast指向最后一个节点时,使其下一个再指向头节点,slow指向空,此时再将node的头节点更新为fast的位置,以此类推,直到循环k次。于是便可得出旋转后的链表
//将fast和slow指针一起走,fast指向最后一个节点时,使其再指向头节点,slow指向空,以此类推,直到循环k次
while(n < k) {
slow = node;
fast = slow -> next;
while(fast -> next) {
slow = slow -> next;
fast = fast -> next;
}
slow -> next = NULL;
fast -> next = node;
node = fast;
n++;
}
return node;
}
完整代码:
/**
* 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) {
return head;
}
struct ListNode* node = head;
struct ListNode* node1 = head;
struct ListNode* slow = head;
struct ListNode* fast = slow -> next;
int n=0,i=0;
while(node1) {
node1 = node1 -> next;
i++;
}
if(k % i == 0) {
return head;
} else {
k = k % i;
}
while(n < k) {
slow = node;
fast = slow -> next;
while(fast -> next) {
slow = slow -> next;
fast = fast -> next;
}
slow -> next = NULL;
fast -> next = node;
node = fast;
n++;
}
return node;
}