61. Rotate List

61. Rotate Listarrow-up-right

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)

Last updated