题解 | #调整牛群顺序#

调整牛群顺序

https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4

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 n int整型
     * @return ListNode类
     */
    public ListNode moveNthToEnd (ListNode head, int n) {
        // write code here
        if(head==null||head.next==null)return head;
        if(n==1)return head;
        ListNode pre=head;
        ListNode end=head;
        ListNode temp=head;
        int size=1,index=0;
        while(end.next!=null){
            size++;
            end=end.next;
            
        }
        if(n==size){
            head=head.next;
            temp.next=null;
            end.next=temp;
            return head;
        }
        while(pre.next.next!=null){
            index++;
            if(index==size-n)
            {
                temp=pre.next;
                pre.next=pre.next.next;
                temp.next=null;
                end.next=temp;
                return head;
            }
            pre=pre.next;
        }
        return head;


    }
}

全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
牛客583549203号:腾讯还好,况且实习而已,实习生流动性很大,属于正常现象,记得和HR委婉解释
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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