LinkedList - 61. Rotate List

时间:2022-07-25
本文章向大家介绍LinkedList - 61. Rotate List,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

61. Rotate List

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取模之后得到实际真实需要移动的次数,总长度减去这个次数,就能得到该节点位置。

代码: 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 (head == null || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode fast = dummy, slow = dummy;
        int len; // get list len;
        for (len = 0; fast.next != null; len++) fast = fast.next;
    
        // find rotate node
        for (int i = len - k % len; i > 0; i--) slow = slow.next;
        
        // rotate
        fast.next = dummy.next;
        dummy.next = slow.next;
        slow.next = null;
        
        return dummy.next;
    }
}