题目描述
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
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
方法思路
Approach1:
class Solution {
public ListNode rotateRight(ListNode head, int k) {
//Runtime: 8054 ms, faster than 5.01%
//Memory Usage: 38.7 MB
if(head == null || head.next == null)
return head;
while(k > 0){
head = rotateOnceTime(head);
k--;
}
return head;
}
public ListNode rotateOnceTime(ListNode head){
// ListNode con = head;
ListNode cur = head;
while(cur.next.next != null)
cur = cur.next;
// 循环结束后,cur 为尾部倒数第二个结点
ListNode tail = cur.next;
cur.next = cur.next.next;//令cur成为尾结点
tail.next = head;//tail结点成为头结点
return tail;
}
}
Approach2:
The nodes in the list are already linked, and hence the rotation basically means
To close the linked list into the ring.
To break the ring after the new tail and just in front of the new head.
class Solution {
//Runtime: 6 ms, faster than 100.00%
//Memory Usage: 38.1 MB, less than 20.71%
public ListNode rotateRight(ListNode head, int k) {
// base cases
if (head == null) return null;
if (head.next == null) return head;
// close the linked list into the ring
ListNode old_tail = head;
int n;
for(n = 1; old_tail.next != null; n++)
old_tail = old_tail.next;
old_tail.next = head;//step1、2
// n 为链表的长度
// find new tail : (n - k % n - 1)th node;实际上是(n - k % n)th node
// and new head : (n - k % n)th node;实际上是(n - k % n + 1)th node
ListNode new_tail = head;
for (int i = 0; i < n - k % n - 1; i++)
new_tail = new_tail.next;
ListNode new_head = new_tail.next;
// break the ring
new_tail.next = null;//step3、4
return new_head;
}
}
Complexity Analysis
Time complexity : O(N) where Nis a number of elements in the list.
Space complexity : O(1) since it's a constant space solution.