题解 | #调整牛群顺序#
调整牛群顺序
https://www.nowcoder.com/practice/a1f432134c31416b8b2957e66961b7d4
考察的知识点:链表的遍历、链表交换顺序;
解答方法分析:使用快慢指针方法,将fast指针移动到第n个节点,然后同时移动fast和slow指针,直至fast指向链表末尾,此时slow指向倒数第(n+1)个节点,将target指向待移动节点,接着画图分析得出结果。
所用编程语言:JAVA;
完整编程代码:↓
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; for (int i = 0; i < n; i++) { fast = fast.next; } 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; } }