给定一个链表,旋转链表,将链表每个节点向右移动 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
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k)
{
if(NULL==head || NULL==head->next)
{
return head;
}
struct ListNode* last=head;
int count=1;
while(last->next)
{
count++;
last=last->next;
}
k%=count;
if(0==k)
{
return head;
}
int i=1;
struct ListNode* tmp=head;
while(i<count-k)
{
tmp=tmp->next;
i++;
}
struct ListNode* start=tmp->next;
tmp->next=NULL;
last->next=head;
return start;
}
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k)
{
if(NULL==head || NULL==head->next)
{
return head;
}
int count=1;
ListNode* last=head;
while(last->next)
{
count++;
last=last->next;
}
k%=count;
if(0==k)
{
return head;
}
ListNode* tmp=head;
int i=1;
while(i<count-k)
{
tmp=tmp->next;
i++;
}
ListNode* start=tmp->next;
tmp->next=NULL;
last->next=head;
return start;
}
};
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if None==head or None==head.next:
return head
count=1
last=head
while last.next:
last=last.next
count+=1
k%=count
if 0==k:
return head
tmp=head
i=1
while i<count-k:
tmp=tmp.next
i+=1
start=tmp.next
tmp.next=None
last.next=head
return start