【LeetCode】Rotate List 解题报告

本文介绍了一种将链表向右循环移动k个位置的方法,特别关注了k可能大于链表长度的情况。通过实例演示了如何实现这一操作,并提供了一个完整的Java代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【题目】

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

【解析】

题意:把链表循环右移k个结点。

不是很难,主要是几个易错点:1)k 可能大于等于链表长度!!!2)链表为空或长度为1。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head == null || n < 1) return head;
        
        //遍历链表求其长度,并找到尾部
        ListNode node = head;
        ListNode tail = null;
        ListNode newhead = null;
        int len = 0;
        while (node != null) {
            len++;
            tail = node;
            node = node.next;
        }
        
        //只有一个结点时,返回原链表即可
        if (len == 1 || n % len == 0) return head;
        
        //把链表首位拼接
        tail.next = head;
        
        //找到右移后的链表尾部
        node = head;
        int i = 1;
        while (i != len - n % len) {
            i++;
            node = node.next;
        }
        newhead = node.next;
        node.next = null;
        
        return newhead;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值