题解 | #调整牛群顺序#
调整牛群顺序
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
List<Integer> list = new LinkedList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
int value = list.get(list.size() - n);
list.remove(list.size() - n);
list.add(value);
ListNode node = new ListNode(0);
ListNode result = node;
for (int i = 0; i < list.size(); i++) {
node.next = new ListNode(list.get(i));
node = node.next;
}
return result.next;
}
}
本题考察的知识点是链表,所用编程语言是java。
我们将整条链表每个结点的值存储在集合中,然后将倒数第n个结点放在集合末尾,最后重建链表。

