每日一题---LeetCode19(删除链表的倒数第 N 个结点)

题目:给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

 

package com.test58_LeetCode;

public class E03LeetCode19 {
    /* 方法1
    recursion(ListNode p=1, int n=2) {
        recursion(ListNode p=2, int n=2) {
            recursion(ListNode p=3, int n=2) {
                recursion(ListNode p=4, int n=2) {
                    recursion(ListNode p=5, int n=2) {
                        recursion(ListNode p=null, int n=2) {
                            return 0;
                        }
                        return 1;
                    }
                    return 2;
                }
                if(返回值 == n == 2) {
                    删除
                }
                return 3;
            }
            return 4;
        }
        return 5;
    }
    */
    //方法1
    public ListNode removeNthFromEnd(ListNode head , int n){
        //加哨兵,可以防止第一个元素(倒数最后一个元素)删除不掉。
        //recursion递归是通过  p  p上一个--->p下一个 节点,所以第一个节点没有上一个节点,所以会漏掉第一个节点
        ListNode s = new ListNode(-1, head);
        recursion(s,n);
        return s.next;
    }
    private int recursion(ListNode p , int n){
        if(p == null){
            return 0;
        }
        int r = recursion(p.next, n);
        if(r == n){
//            删除倒数节点,跳过该节点
            p.next = p.next.next;
        }
        return r+1;
    }
    /*
        n=2
        p1
        p2
        s -> 1 -> 2 -> 3 -> 4 -> 5 -> null

             p2
        s -> 1 -> 2 -> 3 -> 4 -> 5 -> null

                  p2
        s -> 1 -> 2 -> 3 -> 4 -> 5 -> null

        p1             p2
        s -> 1 -> 2 -> 3 -> 4 -> 5 -> null

                       p1             p2
        s -> 1 -> 2 -> 3 -> 4 -> 5 -> null
     */
    //方法2
    public ListNode removeNthFromEnd2(ListNode head , int n){
        ListNode s = new ListNode(-1,head);
        ListNode p1 =s;
        ListNode p2 =s;
        for (int i = 0 ; i < n + 1 ; i++){
            p2 = p2.next;
        }
        while (p2 != null){
            p1 = p1.next;
            p2 = p2.next;
        }
        p1.next = p1.next.next;
        return s.next;
    }
    public static void main(String[] args) {
        ListNode list = ListNode.of(1, 2, 3, 4, 5);
        ListNode head = new E03LeetCode19().removeNthFromEnd2(list, 2);
        System.out.println(head);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值