将链表旋转次数与链表长度取余,快慢指针遍历一次旋转即可
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);
}
}