题解 | #牛群旋转#
牛群旋转
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 ListNode temp=head; if(head==null||head.next==null)return head; int num=0; while(temp!=null){ temp=temp.next; num++; } if(k>num)k=k%num; head=reverse(head,1,num); ListNode pre=reverse(head,1,k); ListNode end=reverse(pre,k+1,num); System.out.print(666); return pre; } public ListNode reverse(ListNode head,int left,int right){ ListNode pre=null; ListNode cur=head; ListNode end=head; ListNode point=null; for(int i=1;i<left;i++){ cur=cur.next; if(point==null)point=head; else point=point.next; } for(int i=0;i<right;i++){ end=end.next; } if(end!=null)pre=end; while(cur!=end){ ListNode temp=cur.next; cur.next=pre; pre=cur; cur=temp; } if(end==null&&point!=null){ point.next=pre; } return pre; } }