题解 | #调整牛群顺序#

调整牛群顺序

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;


    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
“校招”、“3-5年经验”
xiaolihuamao:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
头顶尖尖的程序员:我是26届的不太懂,25届不应该是找的正式工作吗?为什么还在找实习?大四还实习的话是为了能转正的的岗位吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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