题目
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 = 2Output: 4->5->1->2->3->NULLExplanation:rotate 1 steps to the right: 5->1->2->3->4->NULLrotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4Output: 2->0->1->NULLExplanation:rotate 1 steps to the right: 2->0->1->NULLrotate 2 steps to the right: 1->2->0->NULLrotate 3 steps to the right: 0->1->2->NULLrotate 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 headlet len = 1let last = headwhile (last.next) {len++last = last.next}k %= lenif (!k) return headlet p = headlet count = len - 1while (count !== k) {p = p.nextcount--}let newHead = p.nextp.next = nulllast.next = headreturn newHead}
