问题描述
给定一个链表,旋转链表,将链表每个节点向右移动 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<iostream>
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<len && cin>>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<<p->val<<"-->";
p=p->next;
}
cout<<"tail\n";
}
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
实现思路
循环k次,每一次都将链表尾结点变首节点:
每次循环在寻找链表尾结点时,使用一个pretail指向尾结点的前驱。然后让pretail指向NULL,并让尾结点指向头结点,同时让head==尾结点。
代码实现
#include<iostream>
#include<stdio.h>
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) {
//完成本函数
if(head==NULL) return head;
if(head->next==NULL) return head;//链表只有一个结点时,无论k为多少,旋转之后与原链表一样
if(k==0) return head;
for(int i = 0;i<k;i++){
ListNode *tail = head;
ListNode *pretail;
ListNode *q = head;
while(tail->next){//找尾结点及尾结点前驱
pretail = tail;
tail = tail->next;
}
pretail->next = NULL;
tail->next = head;
head = tail;
}
return head;
}
};
ListNode *createByTail()
{
ListNode *head;
ListNode *p1,*p2;
int n=0,num;
int len;
cin>>len;
head=NULL;
while(n<len && cin>>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<<p->val<<"-->";
p=p->next;
}
cout<<"tail\n";
}
int main()
{
int k;
ListNode* head = createByTail();
cin>>k;
head=Solution().rotateRight(head,k);
displayLink(head);
return 0;
}