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