您的位置:首页 > 其它

Rotate List

2016-03-21 12:46 218 查看
Description:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example: Given 1->2->3->4->5->nullptr and k = 2, return 4->5->1->2->3->nullptr.

分析

先遍历一遍,得出链表长度 len,注意 k 可能大于 len,因此令 k% = len。将尾节点 next 指针

指向首节点,形成一个环,接着往后跑 len − k 步,从这里断开,就是要求的结果了。

#include <iostream>
#include <limits.h>

using namespace std;

class LNode
{
public:
int val;
LNode *next;
LNode(int x):val(x),next(nullptr) { };
};

class Solution
{
public:
LNode *rotateList(LNode *L,int k)
{
if ( L == nullptr || k == 0)
return L;
int len = 1;
LNode *p = L;   //p used to traverse the list
//cout<<p->val;
while(p->next)
{
++len;
p = p->next;
}
//cout<<len;

k = len - k%len;
//cout<<k;
p->next = L;    // end to end

while (k)
{
p = p->next;
--k;

}

L = p->next;    // new head node
p->next = nullptr;  //break the ring

return L;
}
};

int main(void)
{
//1->2->3->4->5->nullptr;

LNode *List = new LNode(INT_MIN);   //create head node
LNode *ptr = List;
int n;  //input the number
cout<<"input the number(non-negtive): ";
cin>>n;

//create the list
cout<<"input the value"<<endl;
for (int i = 0; i < n; ++i)
{
int value;
cin>>value;
ptr->next = new LNode(value);
ptr = ptr->next;
cout<<ptr->val;
if (i < n-1)
cout<<"->";

}
cout<<endl;

Solution solution;
int k = 2;

LNode *ret = solution.rotateList(List->next,k);

LNode *pointer = ret;

//output and delete the list
delete List;    //delete head node

while(pointer)
{
LNode *del = pointer;
cout<<pointer->val;

if (pointer->next != nullptr)
cout<<"->";
pointer = pointer->next;

delete del;
}

cout<<endl;

return 0;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: