题解 | #调整牛群顺序#
调整牛群顺序
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
// 1. 处理明显的特殊情况
if (head == null || head.next == null || n == 1) return head;
// 2. 找到第n个节点的前驱节点,这里采用双指针,让快指针先走n步,然后再与慢指针一起走,当快指针到末尾,慢指针就是要找的指针
ListNode pre = head;
ListNode fast = head;
while (n-- != 0 && fast.next != null) {
fast = fast.next;
}
// 处理特殊情况:交换首尾(如果快指针在先走的过程中到达了末尾,那就需要特殊处理后续)
if (fast.next == null) {
ListNode cur = head;
head = head.next;
cur.next = null;
fast.next = cur;
return head;
}
while (fast != null && fast.next != null) {
fast = fast.next;
pre = pre.next;
}
// 3. 找到最后一个节点: 此时fast指向最后一个节点,pre则是前序节点
ListNode cur = pre.next;
pre.next = pre.next.next;
cur.next = null;
fast.next = cur;
// 4. 返回
return head;
}
}
查看9道真题和解析