zoukankan      html  css  js  c++  java
  • [LeetCode] 61. Rotate List

    Given the head of a linked list, rotate the list to the right by k places.

    Example 1:

    Input: head = [1,2,3,4,5], k = 2
    Output: [4,5,1,2,3]
    

    Example 2:

    Input: head = [0,1,2], k = 4
    Output: [2,0,1]

    Constraints:

    • The number of nodes in the list is in the range [0, 500].
    • -100 <= Node.val <= 100
    • 0 <= k <= 2 * 109

    旋转链表。

    题意很简单,给一个linked list和一个数字k,请你对linked list向右rotate K次,输出rotate后的结果。因为是单链表所以没法从右往左遍历链表。思路是将input先连成一个环,然后在新的head节点和其之前一个节点处断开即可。代码里面注意几个细节。

    1. 算K的长度的时候,注意有可能K是大于链表长度len的,需要取余;

    2. 22行的for loop是遍历到新的head节点之前的那个节点,然后再将其跟新的head断开;

    跑一个例子

    1 - 2 - 3 - 4 - 5, k = 2

    先移动到链表末端,得到长度len = 5

    1 - 2 - 3 - 4 - 5

    |______________|

    h

                   h

    将链表末端再连到head节点,形成一个环

    因为需要往右rotate 2次,所以实际上是要将head指针往后移动len - k次,这样head指针会在新的head之前的一个节点上(4)。此时新的head节点是head.next

    最后将4和5之间的连接断开即可

    时间O(n)

    空间O(1)

    JavaScript实现

     1 /**
     2  * @param {ListNode} head
     3  * @param {number} k
     4  * @return {ListNode}
     5  */
     6 var rotateRight = function(head, k) {
     7     // corner case
     8     if (head == null || head.next == null) {
     9         return head;
    10     }
    11 
    12     // normal case
    13     let len = 1;
    14     let index = head;
    15     while (index.next !== null) {
    16         index = index.next;
    17         len++;
    18     }
    19     index.next = head;
    20 
    21     // loop again
    22     for (let i = 1; i < len - (k % len); i++) {
    23         head = head.next;
    24     }
    25     let res = head.next;
    26     head.next = null;
    27     return res;
    28 };

    Java实现

     1 class Solution {
     2     public ListNode rotateRight(ListNode head, int k) {
     3         // corner case
     4         if (head == null || head.next == null) {
     5             return head;
     6         }
     7         // get the length
     8         ListNode index = head;
     9         int len = 1;
    10         while (index.next != null) {
    11             index = index.next;
    12             len++;
    13         }
    14 
    15         index.next = head;
    16         for (int i = 1; i < len - k % len; i++) {
    17             head = head.next;
    18         }
    19         ListNode res = head.next;
    20         head.next = null;
    21         return res;
    22     }
    23 }

    相关题目

    61. Rotate List

    189. Rotate Array

    LeetCode 题目总结

  • 相关阅读:
    自动生成build.xml文件
    【luogu 3371】【模板】单源最短路径
    【noip 2005】 采药
    【poj 3253】Fence Repair
    【poj 3069】Saruman's Army
    【poj 3617】Best Cow Line
    【poj 2386】Lake Counting
    【noip 2010】 关押罪犯
    【rqnoj 343】mty的考验
    【codevs 1073】家族
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11798688.html
Copyright © 2011-2022 走看看