LeetCode_Rotate List
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->NULL and k = 2,
return 4->5->1->2->3->NULL.
巨没劲的一道题,当k>length 时,我以为origin list 不动就行,结果好些case过不了,看了别人的代码才知道要 k%= length 真心想不通为什么,也懒得弄这种恶心的东西。面试遇到这种题目直接问面试官这种奇葩情况怎么处理就行。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL || k == 0) return head;
ListNode *p, *q;
p = head;q= p;
while(q &&--k){
q = q->next;
}
if(k >0 || NULL == q) return head;
ListNode *pre = NULL; while(q->next){
pre = p;
p = p->next;
q = q->next;
}
q ->next = head;
head = p;
pre ->next = NULL;
return head; }
};
LeetCode_Rotate List的更多相关文章
- LeetCode_Rotate Image
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). ...
随机推荐
- BZOJ3394: [Usaco2009 Jan]Best Spot 最佳牧场
3394: [Usaco2009 Jan]Best Spot 最佳牧场 Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 11 Solved: 9[Sub ...
- cf498C Array and Operations
C. Array and Operations time limit per test 1 second memory limit per test 256 megabytes input stand ...
- 读<<如何阅读一本书>>乱七八糟的笔记1
阅读层次 第一层:基础阅读 第二层:检视阅读 系统化略读 第三层:分析阅读 第四层:主题阅读(比较阅读) 第二层:检视阅读 1.有系统的粗读或略读 (1)先看书名页,然后如果有序就先看序 (2)研究目 ...
- HDU_2040——判断亲和数
Problem Description 古希腊数学家毕达哥拉斯在自然数研究中发现,220的所有真约数(即不是自身的约数)之和为: 1+2+4+5+10+11+20+22+44+55+110=284. ...
- 消除JavaScript闭包的一般方法
JavaScript 的闭包是一个其主动发展的特性, 也是一个被动发展的特性. 也就是说, 一方面, JS 有了闭包能更好解决一些问题. 另一方面, JS 为了解决某些问题, 而不得不使用闭包勉强来解 ...
- UUID详解
什么是UUID? UUID是Universally Unique Identifier的缩写,它是在一定的范围内(从特定的名字空间到全球)唯一的机器生成的标识符.UUID具有以下涵义: 经由一定的算法 ...
- git 错误
1 执行 Git add somefile 的时候,出现 如下 错误: If no other git process is currently running, this probably m ...
- 为什么p标签不能嵌套div??
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- JDBC批量插入数据效率分析
对于需要批量插入数据库操作JDBC有多重方式,本利从三个角度对Statement和PreparedStatement两种执行方式进行分析,总结较优的方案. 当前实现由如下条件: 执行数据库:Mysql ...
- js中的循环语句
js中的循环语句可分为三种:1.while:2.do……while:3.for. while的语法为 while (exp) { //statements;} var a=1,b=0; whil ...