题解 | #调整牛群顺序#

调整牛群顺序

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) {
        if (n == 1) {
            return head;
        }
        ListNode preHead = new ListNode(-1);
        preHead.next = head;
        ListNode fast = preHead;
        ListNode slow = preHead;
        // 将fast指针移动到链表的第n个节点
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        // 同时移动fast和slow指针,直到fast指针达到链表末尾
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        ListNode target = slow.next;
        slow.next = slow.next.next;
        target.next = null;
        fast.next = target;

        return preHead.next;
    }
}

解题思路分析:将fast指针移动到链表的第n个节点,同时移动fast和slow指针,直到fast指针达到链表末尾

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务