给定一个链表,旋转链表,将链表每个节点向右移动 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
可使用以下代码,完成其中的rotateRight函数,其中形参head指向无头结点单链表,k为旋转的步数,返回旋转后的链表头指针。
#include输入说明using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(NULL) {} ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode* rotateRight(ListNode* head, int k) { //完成本函数 } }; ListNode *createByTail() { ListNode *head; ListNode *p1,*p2; int n=0,num; int len; cin>>len; head=NULL; while(n >num) { p1=new ListNode(num); n=n+1; if(n==1) head=p1; else p2->next=p1; p2=p1; } return head; } void displayLink(ListNode *head) { ListNode *p; p=head; cout<<"head-->"; while(p!= NULL) { cout< val<<"-->"; p=p->next; } cout<<"tailn"; } int main() { int k; ListNode* head = createByTail(); cin>>k; head=Solution().rotateRight(head,k); displayLink(head); return 0; }
首先输入链表长度len,然后输入len个整数,以空格分隔。
再输入非负整数k
5 1 2 3 4 5 2输出示例
head-->4-->5-->1-->2-->3-->tail代码思路
若共有n个数据,将链表分为两段,后n-k个数据作为一个整体,使用头插法插入
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
//不移动位置的情况:1、链表为空;2、只有一个元素;3、k=0
if(head==NULL||head->next==NULL||k==0)
return head;
//计算链表长度
int len=1;
ListNode *end=head;
while(end->next){
len++;
end=end->next;
}
//找到断开节点
k=k%len;
ListNode *p=head;
for(int i=0;i
p=p->next;
}
end->next=head;
//更新头指针
head=p->next;
p->next=NULL;
return head;
}
};



