19. 删除链表的倒数第 N 个结点

image.png

快慢指针

为了避免删除头节点时多写判断,新建 temp 临时节点,tempnext 指向 head,最后返回 tempnext

执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户 内存消耗:36 MB, 在所有 Java 提交中击败了98.72% 的用户

  1. class Solution {
  2. public ListNode removeNthFromEnd(ListNode head, int n) {
  3. ListNode temp = new ListNode(0, head);
  4. ListNode fast = head;
  5. ListNode slow = temp;
  6. for (int i = 0; i < n; i++) {
  7. fast = fast.next;
  8. }
  9. while (fast != null) {
  10. slow = slow.next;
  11. fast = fast.next;
  12. }
  13. slow.next = slow.next.next;
  14. return temp.next;
  15. }
  16. }

计算链表长度

执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户 内存消耗:36.3 MB, 在所有 Java 提交中击败了75.82% 的用户

  1. public ListNode removeNthFromEnd(ListNode head, int n) {
  2. // 计算长度
  3. int length = 0;
  4. ListNode temp = head;
  5. while (temp != null) {
  6. temp = temp.next;
  7. length ++;
  8. }
  9. // temp作为临时节点,next指向head
  10. temp = new ListNode(0);
  11. temp.next = head;
  12. ListNode cur = temp;
  13. for (int i = 0; i < length - n; i++) {
  14. cur = cur.next;
  15. }
  16. cur.next = cur.next.next;
  17. return temp.next;
  18. }

使用辅助栈

先把所有节点加入栈,使用栈先进后出的特性,出栈时第 n 个节点就是要删除的节点

执行用时:1 ms, 在所有 Java 提交中击败了20.25% 的用户 内存消耗:37.8 MB, 在所有 Java 提交中击败了5.00% 的用户

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode temp = new ListNode(0, head);
        Stack<ListNode> stack = new Stack<>();
        ListNode cur = temp;

        while (cur != null) {
            stack.push(cur);
            cur = cur.next;
        }

        for (int i = 0; i <= n; i++) {
            cur = stack.pop();
        }
        cur.next = cur.next.next;
        return temp.next;
    }
}