0061. Rotate List (M)

Posted mapoos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了0061. Rotate List (M)相关的知识,希望对你有一定的参考价值。

Rotate List (M)

题目

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

题意

依次将链表最后一个元素移到最前面,共移动k次。

思路

由于k可能大于链表本身长度length,所以先遍历一遍链表得到length,简化 k = k % length,再找到倒数k个元素前的一个元素(即新链表的最后一个元素),以此为分界点,将前半链表接到后半链表的后面。


代码实现

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null) {
            return head;
        }
        
        int length = 1;
        ListNode last = head;
        while (last.next != null) {
            length++;
            last = last.next;
        }
        k = k % length;
        if (k == 0) {
            return head;
        }
        
        // 找到新链表的尾结点
        int count = 1;
        ListNode newLast = head;
        while (count < length - k) {
            newLast = newLast.next;
            count++;
        }
        
        // 找到新链表的头结点,并将前半链表移到最后
        ListNode newHead = newLast.next;
        newLast.next = null;
        last.next = head;
        
        return newHead;
    }
}

javascript

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function (head, k) {
  if (!head || !k) return head

  let len = 1
  let last = head
  while (last.next) {
    len++
    last = last.next
  }

  k %= len
  if (!k) return head

  let p = head
  let count = len - 1
  while (count !== k) {
    p = p.next
    count--
  }
  let newHead = p.next
  p.next = null
  last.next = head

  return newHead
}

以上是关于0061. Rotate List (M)的主要内容,如果未能解决你的问题,请参考以下文章

61.Rotate List

LeetCode OJ 61. Rotate List 考虑边界条件

hdu 6040 -Hints of sd0061(STL)

LeetCode -- 61. Rotate List

HDU 6040 Hints of sd0061 nth_element函数

Python 解leetcode:48. Rotate Image