61. Rotate List
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
My Solutions:
找到list的末尾5,同时计算list的长度
把5和list现在的head1,连成环
用len-k算出需要移的node的前一个。比如如果右移2步,则5 - 2 = 3 之后的nodes会到前面来
找到3,先把3之后的node存成新的head,再把3之后的node变成null
返回新的head,这个head的后面已经和之前的头部相连
Time: O(n); Space: O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null || k == 0) return head;
int len = 1;
ListNode node = head;
// 找到list的末尾node
while (node.next != null) {
node = node.next;
len++;
}
if (k % len == 0) return head;
k = k % len; //可能要右移超过1圈
node.next = head; //最后一个node连上head,变成环
// 找到需要分割的地方
for (int i = 1; i < len - k; i++) {
head = head.next;
} //此时head = 3
ListNode res = head.next; //res = 4
head.next = null; // 3的之后是null
return res;
}
}
Last updated