题解 | #牛群旋转#

牛群旋转

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;

    }
}

全部评论

相关推荐

昨天 17:59
已编辑
长江大学 Java
点赞 评论 收藏
分享
刘湘_passion:太强了牛肉哥有被激励到
点赞 评论 收藏
分享
你背过凌晨4点的八股文么:简历挂了的话会是流程终止,像我一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务