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 步,从这里断开,就是要求的结果了。
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; }
相关文章推荐
- codeforces 653C C. Bear and Up-Down(乱搞题)
- Spring通过@Value注解注入属性的几种方式
- 【源代码】指标权重赋权
- CF_1B_Spreadsheets 进制转换
- 你在编程的时候浪费了多少时间?
- 你在编程的时候浪费了多少时间?
- iOS-swift-tableview隐藏多余的cell分割线
- [LeetCode][数论]Move Zeroes
- 使用jsvc启动tomcat
- CocoaPosd 详解
- CDOJ 1045 Lovely princess
- ProgressDialog,数据加载显示
- 十天学会web标准(DIV+CSS)系列(六)html列表
- Android Studio中集成fresco,解决冲突的问题。
- iOS-swift-AFNetworking使用事例
- Java的n++问题
- CDOJ 1034 AC Milan VS Juventus
- Java技术_Java千百问(0009)_java开发应该使用什么工具
- 【AudioProfile】设置震动默认开启
- Remove Duplicates from Sorted List