19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Follow up: Could you do this in one pass?
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
方法:
我们可以使用两个指针 first 和 second 同时对链表进行遍历, 并且first 比 second 超前 n 个节点,当 first 遍历到链表的末尾时,second 就恰好处于倒数第 n 个节点。
如果能找到倒数第 n 个节点的前驱节点而不是倒数第 n 个节点的话,删除操作会更加方便。因此我们可以考虑在初始时将 second 指向哑节点。哑节点的next是头节点。
public static class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dumpy = new ListNode(0, head); dumpy.next = head; ListNode first = head; ListNode second = dumpy; for (int i = 0; i < n && first != null; i++) first = first.next; while (first != null) { second = second.next; first = first.next; } if (second.next != null) second.next = second.next.next; else second.next = null; return dumpy.next; }
参考链接:
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list