Given a list, rotate the list to the right by k places, where k is non-negative.

 
Example

Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.

解法一:

 public class Solution {
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length ++;
head = head.next;
}
return length;
} public ListNode rotateRight(ListNode head, int n) {
if (head == null) {
return null;
} int length = getLength(head);
n = n % length; ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy; ListNode tail = dummy;
for (int i = 0; i < n; i++) {
head = head.next;
} while (head.next != null) {
tail = tail.next;
head = head.next;
} head.next = dummy.next;
dummy.next = tail.next;
tail.next = null;
return dummy.next;
}
}

快慢指针  + dummy节点,参考@NineChapter 的代码

解法二:

 class Solution {
public:
/**
* @param head: the list
* @param k: rotate to the right k places
* @return: the list after rotation
*/
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL) {
return head;
} int len = ;
for (ListNode *node = head; node != NULL; node = node->next) {
len++;
}
k = k % len; if (k == ) {
return head;
} ListNode *fast = head;
for (int i = ; i < k; i++) {
fast = fast->next;
} ListNode *slow = head;
while (fast->next != NULL) {
slow = slow->next;
fast = fast->next;
} fast->next = head;
head = slow->next;
slow->next = NULL; return head;
}
};

不带dummy节点的解法,参考@NineChapter 的代码

最新文章

  1. Android开发学习之路-该怎么学Android(Service和Activity通信为例)
  2. MySQL服务器安装配置-非安装版、windows版
  3. DataTime格式化大全(转载)
  4. WordPress数据库研究 (转)
  5. C# 在SQLite数据库中存储图像 z
  6. deciaml(十进制浮点运算)
  7. iOS: NSMutableArray的方法removeObject:inRange:
  8. Java 快排
  9. 概率与统计推断第二讲homework
  10. 论文选读二:Multi-Passage Machine Reading Comprehension with Cross-Passage Answer Verification
  11. 【EF6学习笔记】(二)操练 CRUD 增删改查
  12. SQL的日期转换
  13. js设置cookie(原生js)
  14. css优化建议
  15. 【BZOJ】1016: [JSOI2008]最小生成树计数
  16. 大数据学习--day15(常用类:Date--DateFormat--SimpleDateFormat--File--包装类)
  17. 联想yoga table2 1371f 进入bios 的巧妙方法
  18. python之gevent模块实现协程
  19. BZOJ1037 ZJOI2008生日聚会(动态规划)
  20. SprimgMVC学习笔记(一)—— SpringMVC入门

热门文章

  1. 为什么控制台console.log一个值,总是会多一个undefined
  2. Android 开发之 ---- bootloader (LK)
  3. 将EC2的Sql Server 计划任务的方式备份到s3上
  4. [置顶] struts2+hibernate+spring整合(annotation版)
  5. 【转】dependency injection 的例子
  6. mac 下安装 plink
  7. Junit核心——测试集(TestSuite)
  8. Linux 倒引号、单引号、双引号
  9. next 前缀字符串
  10. Android so文件生成