题解 | #调整牛群顺序#

调整牛群顺序

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)  {
        ListNode tempNode = head;
        /*
         * 临界条件:
         * 1. ListLength=1
         * 2. n=1。
         * 3. ListLength==n
         */
        // 临界条件 ListLength=1
        if (tempNode.next == null) {
            return head;
        }
        int ListLen = 0;
        ListNode tailNode = null;
        //统计链表长度ListLen
        while (tempNode != null) {
            ListLen += 1;
            if (tempNode.next == null) {
                if (n == 1) {
                    // 临界条件 n=1
                    return head;
                }
                tailNode = tempNode;
            }
            tempNode = tempNode.next;
        }
        // 临界条件ListLength==n
        tempNode = head;
        if (ListLen == n) {
            tailNode.next = head;
            head = head.next;
            tailNode.next.next = null;
            return head;
        }
        /*
         * 遍历链表,tailNode指向最后一个节点,得到节点长度为ListLen
         * 指定长度x,从头开始遍历ListLen-x时,preNode指向该位置,tempNode指向其下一个位置
         * preNode.next=preNode.next.next;
         * tailNode.next=tempNode;
         * tempNode.next=null;
         */
        tempNode = head;
        int inden = 0;
        ListNode preNode;
        while (tempNode.next != null) {
            inden += 1;
            if (inden == (ListLen - n)) {
                preNode = tempNode;
                tempNode = tempNode.next;
                preNode.next = preNode.next.next;
                tempNode.next = null;
                tailNode.next = tempNode;
                break;
            }
            tempNode = tempNode.next;
        }
        return head;
    }


}

全部评论

相关推荐

牛客59349152...:没有让你做出个前后端页面,然后又不要你就知足了吧😂
点赞 评论 收藏
分享
搜索部 首先说下timeline8.18,投递8.19,约一面8.21,晚上一面call约二面8.22,上午二面下午oc周末等待(8.23,8.24)8.25,offer一年前,我还是懵懵懂懂,高考完的暑假,只会提前学学高数,未来的画像是什么?我或许无法预测。开学后,自学Python,接单,无数个客户的ddl,偷偷摸摸一个人找自习的地方,这一步步竟然为后来的我,搭建工程能力的基础。大一上,我也要感谢我的第一位老板,让我接触到了实习,师兄带着我一步步入门,看他们写的飞书文档。大一下,导师带我参与企业项目,这让我渐渐发现,应该去实践,增长见识,而非局限当下,盯着自己的小新pro。不久后,第一波投递开始,结果当然是约面极少。盯着简历上的文字和ssob,我开始思考,确实很多可以去提升。带着些许不甘心,继续沉淀,慢慢的约面也越来越多,有的时候两天7场,准备完就接着下一个日程。这一次,也许是刚好到位吧,比较match,面试答的流利,关关难关关过,成为度孝子展望未来,依然是重重挑战,果然只有收到offer的那一刻是开心的。愿在百度星海拆解的每一段代码,都能成为丈量宇宙的诗行;此志终赴星河,而今迈步重铸天阶。屏幕前的你们,在无数个向星海奔赴的日夜,一定一定,会在未来化作群星回响的征程——请永远相信此刻埋首耕耘的自己!!!
一天三顿半:???百度提前批发 offer了?不是统一和正式批排序完再发吗我靠
百度求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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