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 || n == 1) return head;
ListNode hair = head, cur = head, pre = head;
int cnt = 1;
while (cur.next != null) {
cur = cur.next;
cnt++;
}
if (n == cnt) {
cur.next = head;
hair = head.next;
head.next = null;
return hair;
}
for (int i = 0; i < (cnt - n - 1); i++) pre = pre.next;
cur.next = pre.next;
pre.next = pre.next.next;
cur.next.next = null;
return head;
}
}
- 判断head边界值,如果链表节点数少于2个,或者需要调整的节点是尾节点时,则直接返回head;
- 定义3个指针分别指向:虚拟头节点 hair(头节点可能被调整到末尾)、当前节点 cur、需要调整的节点的前一个节点 pre;
- while循环遍历链表将cur移动到链表尾部,并记录下节点数量 cnt
- 特殊情况:当 n == cnt 时,需要将尾节点接到头节点,并将头节点断开,返回头节点的下一个节点作为新的头节点
- 如果是中间某个节点,则先找到调整节点的前一个节点 pre,然后进行调整