旋转链表
题目描述
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
题目作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetb...
题目来源:力扣(LeetCode)
题解作者:WildDuck
分析思路
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//本题解中的fast指针不会比slow每次走快N步,只是比slow指针先出发,二者步伐速度一致,用于形成一个区间
typedef struct ListNode* ListNode_pointer;
struct ListNode* rotateRight(struct ListNode* head, int k)
{
if(head != NULL)
{
ListNode_pointer fast = head;
ListNode_pointer slow = head;
ListNode_pointer save_pointer = NULL;
int list_length=1;
while(fast->next != NULL)
{
fast = fast -> next;
list_length = list_length+1;
}
k = k%list_length;
fast = head;
for(int i = 0; i<k;i++)
{
fast = fast->next;
}
while(fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
if(slow != fast)
{
save_pointer = slow;
slow = slow ->next;
fast->next = head;
save_pointer->next = NULL;
}
else if (slow == fast)
{
slow = head;
}
return slow;
}
else return head;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。