【算法】LC0061旋转链表,基本数据结构链表经典算法

本文介绍了一种使用快慢指针的方法,通过计算链表长度并取余,实现链表旋转操作,使得链表旋转次数与链表长度保持一致。实例代码展示了如何在Java中实现链表的旋转,并提供了创建链表和遍历链表的相关函数。

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

 将链表旋转次数与链表长度取余,快慢指针遍历一次旋转即可

import java.util.Scanner;
 class ListNode {
    int val;
    ListNode next;
    ListNode() {
    }
    ListNode(int val) {
        this.val = val;
    }
}

public class LC0061 {
    public static ListNode rotateRight(ListNode head, int k) {
        if(k==0||head==null||head.next==null)return head;
        //计算链表长度
        int len=0;
        ListNode root=head;
        while (root!=null){
            len++;
            root=root.next;
        }
        k=k%len;
        if(k==0)return head;
        ListNode fast = head;
        while (k > 0) {
            fast = fast.next;
            k--;
        }
        // 快慢指针再一起同步前进,直至fast走到尾节点停:
        ListNode slow = head;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        // 此时的慢指针slow的下一个节点就是旋转后的新头,原尾节点fast串连到老头head上:
        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = head;
        return newHead;
    }

    //递归创建链表
     public static ListNode createListnode(int s[],int i){
            if(i==s.length)return null;
            ListNode listNode=new ListNode(s[i]);
            listNode.next=createListnode(s,i+1);
            return listNode;
     }
     //遍历显示链表
     public static void showListnode(ListNode root){
        if(root==null)return;
        if(root.next==null) System.out.print(root.val);
        else System.out.print(root.val+"-->");
        showListnode(root.next);
     }

    public static void main(String[] args) {
        System.out.println("请输入链表:(以空格分割)");
        Scanner sc=new Scanner(System.in);
        String line=sc.nextLine();
        String[] lines =line.split(" ");
        int s[]=new int[lines.length];
        int q=0;
        for(String string:lines){
            s[q]=Integer.parseInt(string);
            q++;
        }
        ListNode head=createListnode(s,0);
        System.out.println("输入旋转次数");
        int num=sc.nextInt();
        System.out.println("初始链表");
        showListnode(head);
        head=rotateRight(head,num);
        System.out.println();
        System.out.println("旋转后");
        showListnode(head);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值