leetcode 之Rotate List 解题思路

本文介绍了一种将链表向右移动k个位置的算法实现,通过双指针技巧完成链表的重新连接,适用于链表操作的学习与实践。

摘要生成于 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) 链表为空或者链表只有一个元素,直接返回原链表

(2)当k等于链表长度,相当于不用右移;当k大于链表长度,相当于只要右移k%(链表长度)个位置

根据给定的例子说明如何右移:

我们找到倒数第k+1个位置,用两个指针同时遍历;倒数第k+1个位置即为3,则它的后面的元素需要被插入到头结点的位置。(这里设置一个Head指针作为哨兵,用来简化头插操作。)同时原链表最后一个元素即为5的next指针应该指向head。最后返回Head.next即可。


代码如下:

/**
 * 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 || head.next == null) return head;//情况一
        int length = 0;
        ListNode p = head;
        while(p != null){
            length++;
            p = p.next;
        }
        int times = n % length; //times表示右移的个数
        if(times == 0) return head; //如果右移个数为0,则不作处理,否则做如下处理
        ListNode Head = new ListNode(-1);
        Head.next = head;
        ListNode after = head;
        ListNode before = Head;
        for(int i = 0; i < times + 1; i++){
            before = before.next;
        }
        while(before.next != null){
            after = after.next;
            before = before.next;
        }
        ListNode split = after.next;
        after.next = null;
        Head.next = split;
        before.next = head;
        return Head.next;
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值