题解 | #调整牛群顺序#

调整牛群顺序

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;
    }


}

全部评论

相关推荐

07-24 03:49
门头沟学院 Java
牛客73769814...:这种小作坊去了也费劲
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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