美文网首页
leetcode题目61. 旋转链表

leetcode题目61. 旋转链表

作者: castlet | 来源:发表于2022-02-28 22:29 被阅读0次

    题目描述

    链接:https://leetcode-cn.com/problems/rotate-list/
    给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

    示例

    输入:head = [1,2,3,4,5], k = 2
    输出:[4,5,1,2,3]
    

    代码

        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || k <= 0) {
                return head;
            }
    
            int length = 1; // 链表长度
            ListNode tempHead = head;
            ListNode lastNode = null; // 链表最后一个节点
            // 计算链表长度
            while (tempHead.next != null) {
                length ++;
                tempHead = tempHead.next;
            }
            lastNode = tempHead;
    
            // 如果k大于链表长度,则取余数
            if (k >= length) {
                k = k % length;
            }
    
            // 如果k = 0,表示不用旋转,则直接返回head
            if (k == 0) {
                return head;
            }
    
            // 找到旋转后链表的头部位置
            tempHead = head;
            for (int i = 0; i < length - k - 1; i++) {
                tempHead = tempHead.next;
            }
    
            ListNode newHead = tempHead.next;
            tempHead.next = null; // 断开指向头部的指针
            lastNode.next = head; // 链表最后一个元素执行原始的头节点
            return newHead;
        }
    

    相关文章

      网友评论

          本文标题:leetcode题目61. 旋转链表

          本文链接:https://www.haomeiwen.com/subject/ftmrrrtx.html