【LeetCode】 61. Rotate List 旋转链表(Medium)(JAVA)

【LeetCode】 61. Rotate List 旋转链表(Medium)(JAVA)

题目地址: https://leetcode.com/problems/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 是非负数。

解题方法

1、计算出链表的长度(因为存在:k > len),然后计算出真实需要移动位置:k % len
2、找出需要移动的上一个 node,preNode
3、断开 preNode 的 next,把所有的 node 连起来

/**
 * 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) return head;
        ListNode temp = head;
        int count = 1;
        while (temp != null) {
            if (temp.next == null) break;
            temp = temp.next;
            count++;
        }
        ListNode tail = temp;
        k = k % count;
        temp = head;
        for (int i = 1; i < count - k; i++) {
            temp = temp.next;
        }
        tail.next = head;
        ListNode res = temp.next;
        temp.next = null;
        return res;
    }
}

执行用时 : 1 ms, 在所有 Java 提交中击败了 87.45% 的用户
内存消耗 : 37.9 MB, 在所有 Java 提交中击败了 14.53% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2277

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104878270