题目
思路
- 思路一:遍历,通过双指针,它们相差n步,当先走指针为null时,说明慢走的指针此时在删除节点上
思路二:递归,递归时每次移动一个节点,需要一个全局遍历统计移动位置,当递归到最后一个节点时,我们就开始计数,当它等于n时就说明,此时节点位于要删除的节点,此时返回就跳过一个节点。换种思路理解就是递归相当于一个栈,我们一开始先遍历整个链表入栈,全部入栈结束后,再出栈,当出栈到第n个节点的时候,就跳过这个结点,重新指向另一个节点。
代码
//1.遍历public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null || n <= 0) return head;ListNode dummy = new ListNode(0);dummy.next = head;ListNode prev = dummy, cur = head, tail = head;for (int i = 0; i < n; i++) {tail = tail.next;}while (tail != null) {prev = cur;cur = cur.next;tail = tail.next;}prev.next = cur.next;return dummy.next;}//2.递归int count = 0;public ListNode removeNthFromEnd(ListNode head, int n) {if (head == null) return head;head.next = removeNthFromEnd(head.next, n);count++;if (count == n) return head.next;return head;}
