给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 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
示例 2:
输入: 0->1->2->NULL, k = 4 输出: 2->0->1->NULL 解释: 向右旋转 1 步: 2->0->1->NULL 向右旋转 2 步: 1->2->0->NULL 向右旋转 3 步: 0->1->2->NULL 向右旋转 4 步: 2->0->1->NULL
//==============================================================================
/**
* 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<1)
{
return head;
}
//遍历链表,求长度
struct ListNode *newHead=head, *newTail=NULL;
int len=1;
while(newHead->next)
{
newTail = newHead;
newHead = newHead->next;
len += 1;
}
//重新计算旋转长度
k = k % len;
//如果旋转长度为0,则无需旋转
if(k==0)
{
return head;
}
//旋转第一个结点
newTail->next = NULL;
newHead->next = head;
head=newHead;
k--;
//依次旋转后续所有结点
while(k>0)
{
newHead = head;
while(newHead->next)
{
newTail = newHead;
newHead = newHead->next;
}
newTail->next = NULL;
newHead->next = head;
head=newHead;
k -= 1;
}
return head;
}
//===========================================================================\
/**
* 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<1)
{
return head;
}
int count=1;
struct ListNode *temp;
struct ListNode *newTail;
int first = 0;
while(k>0)
{
temp = head; //备份头结点
while(head->next) //head为尾结点,newTail为倒数第二个结点
{
newTail = head;
head = head->next;
count += 1;
}
//printf("1count = %d, k=%d\n", count,k);
if(first == 0)
first = 1;
if(first==1 && k >= count) //第一次遍历,重新计算旋转长度
{
k = k % count;
//printf("2count = %d, k=%d\n", count,k);
}
if(k==0) //如果旋转长度为0,则无需旋转
{
head = temp;
break;
}
newTail->next = NULL; //倒数第二个结点为新的尾结点
head->next = temp; //尾结点为新的头结点
k -= 1;
}
return head;
}