码迷,mamicode.com
首页 > 其他好文 > 详细

0061. Rotate List (M)

时间:2020-07-11 09:40:09      阅读:39      评论:0      收藏:0      [点我收藏+]

标签:efi   for   rip   ||   ini   amp   list   tno   @param   

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)

标签:efi   for   rip   ||   ini   amp   list   tno   @param   

原文地址:https://www.cnblogs.com/mapoos/p/13282218.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!