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的更多相关文章

  1. LeetCode_Rotate Image

    You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). ...

随机推荐

  1. BZOJ3400: [Usaco2009 Mar]Cow Frisbee Team 奶牛沙盘队

    3400: [Usaco2009 Mar]Cow Frisbee Team 奶牛沙盘队 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 89  Solve ...

  2. Android全屏显示

    requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_ ...

  3. codevs1044:dilworth定理

    http://www.cnblogs.com/submarine/archive/2011/08/03/2126423.html dilworth定理的介绍 题目大意:求一个序列的lds 同时找出这个 ...

  4. [LeetCode] 11. Container With Most Water My Submissions Question 解题思路

    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).  ...

  5. memcached学习——常用命令+基于java客户端的3种简单实现(二)

    常用命令: memcached设计的原则就是简单,所以支持的命令也不是特别多~ 1.查看memcached的状态,主要用于分析内存的使用状况.优化内存分配等 stats 查看memcached的运行状 ...

  6. MySQL日期函数

    1.已知出生日期,求年龄 SELECT '1992-04-10' as birthday, curdate(), ( YEAR (curdate()) - YEAR ('1992-04-10')-1 ...

  7. INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES错误解决方法

    在安装APK文件时出现类似INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES的提示,同时类似的提示如下: Android Launch! adb is run ...

  8. 怎样修复“Windows/System32/Config/System中文件丢失或损坏”故障

    怎样修复“Windows/System32/Config/System中文件丢失或损坏”故障 英文原文引自 http://xphelpandsupport.mvps.org/how_do_i_repa ...

  9. Java基础知识强化33:String类之String类的获取功能

    1. String类的获取功能 int length() // 获取字符串中字符的个数(长度) char charAt(int index)//根据位置获取字符 int indexOf(int ch) ...

  10. Could not find the Visual SourceSafe Internet Web Service connection information

    Visual SourceSafe Internet---------------------------Could not find the Visual SourceSafe Internet W ...