题解 | #调整牛群顺序#
调整牛群顺序
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;
}
}
