题解 | #牛群旋转#
牛群旋转
https://www.nowcoder.com/practice/5137e606573843e5bf4d8ea0d8ade7f4
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode rotateLeft (ListNode head, int k) {
// write code here
if(head==null||head.next==null){
return head;
}
int m =1 ;
ListNode test=head;
ListNode cur=head;
while(test.next!=null){
test=test.next;
m=m+1;
}//m是链表长度
int p=k%m;//用p来计算位移
for(int i =0;i<m-p-1;i++){
cur=cur.next;
}
ListNode temp=cur.next;
ListNode babe=temp;
cur.next=null;
while(temp.next!=null){
temp=temp.next;}
temp.next=head;
return babe;
}
}
查看22道真题和解析
