[LeetCode题解]Leetcode61.旋转链表

129 阅读1分钟

LeetCode61.旋转链表

原题链接

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

题解

遍历:时间复杂度 O(n)O(n)

首先遍历一下整个链表,找到尾结点tail和整个链表的长度len。然后处理一些k的值,k可能会很大,所以k需要和len取余。然后找头结点和尾结点,分别进行len-k次next操作。返回cur。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || k == 0) return head;
        ListNode cur = head;
        ListNode tail = null;
        int len = 1;
        while (cur.next != null) {
            cur = cur.next;
            len ++;
        }
        int n = len - (k % len);
        tail = cur;
        cur.next = head;
        cur = head;
        for (int i = 0; i < n; i ++) {
            cur = cur.next;
            tail = tail.next;
        }
        tail.next = null;
        return cur;
    }
}