[LintCode] Rotate List

本文介绍了一种链表旋转算法,通过将链表构造成环并调整头部指针位置来实现链表向右旋转k个位置的操作。该方法简单高效,避免了不必要的多次遍历。

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

Rotate List

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

Example

Given 1->2->3->4->5 and k = 2, return 4->5->1->2->3.

 

SOLUTION:

这题挺有意思的,怎么操作还能rotate呢?很简单,先把链表变成一个环,然后将头节点向后移动k个位置就行了!具体实现的时候,有些还是应该注意的,避免重复的绕圈怎么办?先记录链表的长度,然后k % len一下,就是直翻转一次就OK了。记住,一定返回新的头的位置,不要返回老的头的位置。

代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public class CurrNode{
        ListNode node;
        CurrNode(ListNode node){
            this.node = node;
        }
    }
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null){
            return null;
        }
        int len = getLen(head);
        k = k % len;
        ListNode preCut = head;
        ListNode curr = head;
        while (k > 0){
            curr = curr.next;
            k--;
        }
        while (curr.next != null){
            curr = curr.next;
            preCut = preCut.next;
        }
        curr.next = head;
        head = preCut.next;
        preCut.next = null; //关键,不然就不是合法链表了
        return head;
    }
    private int getLen(ListNode head){
        if (head == null){
            return 0;
        }
        int len = 0;
        while (head != null){
            head = head.next;
            len++;
        }
        return len;
    }
}
View Code

 

转载于:https://www.cnblogs.com/tritritri/p/4971313.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值