问题描述: 将单链表向右旋转k个位置
思路:1. 找到链表倒数第k+1个节点和尾节点; 2. 原链表的尾节点指向首节点,头结点指向k+1的下一个节点; 3. k+1的next置空,成为真正的尾节点
void ReverseRK(LinkList head, int k)
{
if(head == NULL || head->next == NULL)
return NULL;
ListNode* slow, *fast, *temp;
slow = fast = head->next;
int i;
for(i=0;i<k&&fast;i++)
{
fast = fast->next; // fast先走k步
}
if(i<k)
return NULL; // k超过链表长度
while(fast)
{
fast = fast->next;
slow = slow->next;
}
temp = slow; // temp指向倒数第k+1个节点
slow = slow->next;
fast->next = head->next;
head->next = slow;
temp->next = NULL;
}
网友评论