1. Given a list, rotate the list to the right by k places, where k is non-negative.
  2.  
  3. For example:
  4. Given 1->2->3->4->5->NULL and k = 2,
  5. return 4->5->1->2->3->NULL.

  巨没劲的一道题,当k>length 时,我以为origin list 不动就行,结果好些case过不了,看了别人的代码才知道要 k%= length 真心想不通为什么,也懒得弄这种恶心的东西。面试遇到这种题目直接问面试官这种奇葩情况怎么处理就行。

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode *rotateRight(ListNode *head, int k) {
  12. // Start typing your C/C++ solution below
  13. // DO NOT write int main() function
  14. if(head == NULL || k == 0) return head;
  15. ListNode *p, *q;
  16. p = head;q= p;
  17. while(q &&--k){
  18. q = q->next;
  19. }
  20. if(k >0 || NULL == q) return head;
  21. ListNode *pre = NULL;
  22.  
  23. while(q->next){
  24. pre = p;
  25. p = p->next;
  26. q = q->next;
  27. }
  28. q ->next = head;
  29. head = p;
  30. pre ->next = NULL;
  31. return head;
  32.  
  33. }
  34. };

  

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. Shell continue循环

    [oracle@june ~]$ cat continue.sh for i in a b c d e f g do if [ "$i" = "c" ] the ...

  2. cf581B Luxurious Houses

    The capital of Berland has n multifloor buildings. The architect who built up the capital was very c ...

  3. HDU_2018——母牛产小牛的问题,递推

    Problem Description 有一头母牛,它每年年初生一头小母牛.每头小母牛从第四个年头开始,每年年初也生一头小母牛.请编程实现在第n年的时候,共有多少头母牛?   Input 输入数据由多 ...

  4. 鹿定制|Lu Couture|鹿定制·高级西装礼服私享定制品牌|芙蓉中路明城国际1425

    鹿定制|Lu Couture|鹿定制·高级西装礼服私享定制品牌|芙蓉中路明城国际1425 联系我们

  5. hdu4111 Alice and Bob

    Alice and Bob Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total ...

  6. Spring容器的工具类

    代码实现: package com.ht.util; import java.util.Map; import org.springframework.beans.BeansException; im ...

  7. Lesson2.1:LinkedList、ConcurrentLinkedQueue、LinkedBlockingQueue对比分析

    写这篇文章源于我经历过的一次生产事故,在某家公司的时候,有个服务会收集业务系统的日志,此服务的开发人员在给业务系统的sdk中就因为使用了LinkedList,又没有做并发控制,就造成了此服务经常不能正 ...

  8. Gulp-livereload:实时刷新编码

    实现功能 监听指定目录下的所有文件,实时动态刷新页面 安装(Install) 功能的实现是借助 gulp-connect 插件完成的;所以,首先通过下面命令完成插件安装: npm install -- ...

  9. (转)Eclipse/Myeclipse 注释注释模板

    Window -->preferences --> Java --> Code Style --> Code Templates --> Comments --> ...

  10. SSO跨域解决方案

    单点登录(Single Sign On),简称为 SSO,是目前比较流行的企业业务整合的解决方案之一.SSO的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统.它包括可 以将 ...