Rotate List
来源:互联网 发布:上海海尚琴行淘宝 编辑:程序博客网 时间:2024/04/29 17:04
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;}
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- iOS-swift-tableview隐藏多余的cell分割线
- CDOJ 1045 Lovely princess
- [LeetCode][数论]Move Zeroes
- jQuery简洁nav切换功能
- Spring通过@Value注解注入属性的几种方式
- Rotate List
- SDAU 贪心专题 12 根号问题
- 十天学会web标准(DIV+CSS)系列(七)横向导航菜单
- iOS Socket理论知识
- Android开发笔记(八十三)多语言支持
- webRTC进阶-概览-之二:WebRTC 典型应用架构
- 面向对象下-3
- ccf 网络延时
- Android笔记——六大布局