2 旋转链表(61)
问题描述 :
给定一个链表,旋转链表,将链表每个节点向右移动 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;
}
#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) { //完成本函数 if(!head) return NULL; ListNode *p = head; // 统计长度 int len = 1; while(p->next) { len++; p=p->next; } // 首尾相连 p->next = head; // 找到断点 k %= len; for(p = head; --len != k; p = p->next); // 更改首尾 head = p->next; p->next = NULL; 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; }
posted on 2020-09-04 16:36 Hi!Superman 阅读(176) 评论(0) 编辑 收藏 举报