LeetCode 61. Rotate List
来源:互联网 发布:linux oracle 中文乱码 编辑:程序博客网 时间:2024/04/29 15:46
https://leetcode.com/problems/rotate-list/
一直想给LeetCode 的题目描述跪, 一直说不清楚。此题一个坑是:k >= length(链表),只要k%=n就行,当然这个时候还有坑 n==0
#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <vector>#include <map>#include <iostream>using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };class Solution {public: int calLen(ListNode *head) { int ret =0; while(head) { head = head -> next; ret ++; } return ret; } ListNode* rotateRight(ListNode* head, int k) { int n = calLen(head); if(n)k %= n; if( k == 0 || head == NULL) return head; ListNode *first = head, *preFir = NULL, *ret=NULL; for(int i=0;i<k;i++) { if(first) { preFir=first, first = first->next; } else { return head; } } ListNode *second = head, *preSec = NULL; while(first) { preFir=first; first = first -> next; preSec = second; second = second -> next; } if(preSec) { preSec -> next = NULL; } else { // k == n return head; } preFir -> next = head;// cout << "preFir = " << preFir->val << endl;// cout << "preSec = " << preSec->val << endl;// cout << "head = " << head->val << endl;// show(second);// cout << "((((((((((" << endl; return second; } ListNode *createFromVector (vector <int> ivec) { ListNode *ret = NULL, *pre=NULL, *head=NULL; for(int i=0;i<ivec.size();i++) { pre = ret; ret = (ListNode *) malloc ( sizeof(ListNode) ); //pre -> next = ret; ret->val = ivec[i]; if(i == 0) pre = head = ret; else pre -> next = ret; //cout << ret->val << endl; } ret -> next = NULL; //show(head); return head; } void show(ListNode *head) { while(head) { cout << "show = " << head->val << endl; head = head->next; } cout << "******************" << endl; }};int main() { freopen("61.txt", "r", stdin); int n,k, in; while(cin >> n >> k) { vector <int> ivec; for(int i=0;i<n;i++) { cin >> in; ivec.push_back(in); } Solution s; ListNode *head = s.createFromVector(ivec); s.show( s.rotateRight(head, k) ); } return 0;}
0 0
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- [LeetCode]61. Rotate List
- LeetCode 61. Rotate List
- LeetCode *** 61. Rotate List
- LeetCode 61. Rotate List
- [Leetcode]61. Rotate List
- LeetCode - 61. Rotate List
- 斐讯PSG1208 K1 路由器刷机
- 【设计模式】—-(1)单例模式(创建型)
- 使用hexo和github pages搭建个人博客
- 2013年第四届蓝桥杯C/C++程序设计本科B组省赛
- $.ajax里面不识别ajax传参data里面的键是一个变量的情况
- LeetCode 61. Rotate List
- Java DataInputStream和DataOutputStream 使用例子
- 为Fedora20安装内核
- 让Windows下的应用程序在崩溃的时候写dump文件的代码
- MySql效率问题
- 缓冲区溢出分析第10课:Winamp缓冲区溢出研究
- gson解析json数据格式为object对象
- 实现BlinnPhong 光照的原理
- CSS浮动(float,clear)