博文中会简要介绍Leetcode P0061题目分析及解题思路。
“Rotate List”是一道简单的题目,O(n)时间复杂度就可以解决。不过空间复杂度上也需要O(n),可能有更好的优化,但是空间换时间相对还是划算的。
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL
这道题的思路很直接明了,每次把链表最后的结点移动到头结点之前,移动k
次。
以下是Java的题解代码实现。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0)
return head;
ListNode dummy = new ListNode(0, head);
ListNode tail = dummy.next;
List<ListNode> cache = new ArrayList<>();
cache.add(tail);
while (tail.next != null) {
tail = tail.next;
cache.add(tail);
}
int len = cache.size();
k %= len;
for (int itr=0; itr<k; ++itr) {
cache.get(len-2-itr).next = cache.get(len-1-itr).next;
cache.get(len-1-itr).next = dummy.next;
dummy.next = cache.get(len-1-itr);
}
return dummy.next;
}
}
以下是C++的题解代码实现。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == NULL)
return head;
ListNode *dummy = new ListNode(0, head);
ListNode *tail = dummy->next;
vector<ListNode*> cache;
cache.push_back(tail);
while (tail->next != NULL) {
tail = tail->next;
cache.push_back(tail);
}
int len = cache.size();
k %= len;
for (int itr=len-1; itr>=len-k; --itr) {
cache[itr-1]->next = cache[itr]->next;
cache[itr]->next = dummy->next;
dummy->next = cache[itr];
}
return dummy->next;
}
};