[LeetCode] Rotate List
2014-01-04 04:34
288 查看
问题:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
分析:
注意,当找到split point之后,两段子链表内的相对顺序是不变的。所以我的思路是,先把把链表连成一个环,然后找到相应的split point, 断开即可。
代码:
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (k == 0) return head;
if (!head) return NULL;
if (!head->next) return head;
ListNode *tail = head;
int len = 1;
while (tail->next) {
len ++;
tail = tail->next;
}
tail->next = head;
k = k % len;
for (int i = 1; i < len - k; i ++) {
head = head->next;
}
ListNode *newHead = head->next;
head->next = NULL;
return newHead;
}
};
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
分析:
注意,当找到split point之后,两段子链表内的相对顺序是不变的。所以我的思路是,先把把链表连成一个环,然后找到相应的split point, 断开即可。
代码:
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (k == 0) return head;
if (!head) return NULL;
if (!head->next) return head;
ListNode *tail = head;
int len = 1;
while (tail->next) {
len ++;
tail = tail->next;
}
tail->next = head;
k = k % len;
for (int i = 1; i < len - k; i ++) {
head = head->next;
}
ListNode *newHead = head->next;
head->next = NULL;
return newHead;
}
};
相关文章推荐
- LeetCode刷题笔录 Rotate List
- LeetCode Rotate List
- Leetcode解题-链表(2.2.6)RotateList
- LeetCode 061 Rotate List
- 【Leetcode】Rotate List (lastN)
- [LeetCode]Rotate List
- LeetCode2.2.6(Rotate List)
- [Leetcode] Rotate list 旋转链表
- LeetCode 61. Rotate List(循环右移单链表)
- [Leetcode]Rotate List
- LeetCode Solutions : Rotate List
- leetcode: 61. Rotate List
- [Leetcode]61. Rotate List
- LeetCode-----61. Rotate List(循环旋转链表)
- LeetCode *** 61. Rotate List
- LeetCode 60 Rotate List
- 【LeetCode】61. Rotate List
- [leetcode] Rotate List
- LeetCode 61 — Rotate List(C++ Java Python)
- C实现 LeetCode->Rotate List(双指针大法)(单链表 部分旋转)