问题描述 :
给定一个链表,旋转链表,将链表每个节点向右移动 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<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
算法思想:
先将链表成环,然后找到新的链表尾,链表头,新的链表头在n-k处,那么链表尾在n-k-1处
当k>=n时,链表尾就是n-k%n-1
*/
#include<iostream>
#include<vector>
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 NULL; //空链表
}
if(head->next == NULL)
{
return head; // 只有一个节点
}
//先将链表成环
ListNode *p = head;
int len = 1;
while(p->next)
{
len++;
p = p->next;
}
p->next = head;
//找到新的链表尾断链
ListNode *new_tail = head;
for(int i = 0; i < len - k%len -1; i++)
{
new_tail = new_tail->next;
}
ListNode *new_head = new_tail->next; //新的头节点
new_tail->next = NULL; //尾节点后继为NULL
return new_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;
}