BM9 删除链表的倒数第 n 个节点

在这里插入图片描述
常规解法:用栈,空间复杂度和时间复杂度都是O(n),不满足题目要求

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param n int整型
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        if (head == null || n == 0) {
            return head;
        }
        ListNode pre = head;

        Stack<ListNode> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.next;
        }

        ListNode cur = null;

        while (!stack.isEmpty()) {
            cur = stack.pop();
            if (--n == 0) {
                if (!stack.isEmpty()) {
                    stack.pop().next = cur.next;
                    return pre;
                } else {
                    return pre.next;
                }
            }
        }
        return pre;
    }
}

第二种解法:快慢指针

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param n int整型
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        if (head == null || n == 0) {
            return head;
        }

        ListNode fast = new ListNode(-1);
        fast.next = head;
        while (n > 0) {
            fast = fast.next;
            n--;
        }
        ListNode slow = new ListNode(-1);
        slow.next = head;
        //删除的是头节点
        if (fast.next == null) {
            return head.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值