美文网首页
LeetCode:61. 旋转链表

LeetCode:61. 旋转链表

作者: alex很累 | 来源:发表于2022-05-03 17:14 被阅读0次

    问题链接

    61. 旋转链表

    问题描述

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

    示例


    解题思路

    这道题思路很简单,直接模拟法,将链表连成环,寻找新的头节点、尾节点将环断开,然后返回表头即可;
    寻找新的表头要注意:假设链表长度为length,表头向右跑 length - (k % length)

    代码示例(JAVA)

    /**
     * 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 (k == 0 || head == null || head.next == null) {
                return head;
            }
    
            // 成环,并计算链表长度
            int length = 1; 
            ListNode tail = head;
            while (tail.next != null) {
                length++;
                tail = tail.next;
            }
            tail.next = head;
            k = length - (k % length);
    
            ListNode l1 = tail, l2 = head;
            for(;k > 0; k--) {
                l1 = l1.next;
                l2 = l2.next;
            }
            l1.next = null;
    
            return l2;
        }
    }
    

    执行结果

    相关文章

      网友评论

          本文标题:LeetCode:61. 旋转链表

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