删除链表的倒数第N个节点

 public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode next=new ListNode(-1);
        next.next=head;
        ListNode pre=head,post=head;
        //移动五次
        while(n-->0)
            pre=pre.next;
        
        while(pre!=null){
            pre=pre.next;
            post=post.next;
        }
        
        if(post.next!=null){
             post.val=post.next.val;
             post.next=post.next.next;
        }else{
             post = null;
        }
        
        return next.next;
    }

怎么改都不对啊……出错就出在只有一个节点 n=1的情况,不能返回null。

但,其实返回倒数第K个节点,就是下列方法。按照这个方法来写,必须考虑上述问题。

public ListNode FindKthToTail(ListNode head, int k) {
    if (head == null)
        return null;
    ListNode P1 = head;
    while (P1 != null && k-- > 0)
        P1 = P1.next;
    if (k > 0)
        return null;
    ListNode P2 = head;
    while (P1 != null) {
        P1 = P1.next;
        P2 = P2.next;
    }
    return P2;
}

我这个方法是咋整都不行了,就只能是找别人的方法了。

下面这个方法实在是厉害了,非常灵活。因为后走的这个指针走到的是要删除节点的前一个节点,因为他是重新加了一个newHead,所以不需要考虑要删除节点是原链表头节点的情况,和尾节点的情况……

但是要注意,因为要使后走的指针指向前一个节点,所以前后指针的差距应该是(n+1)

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode first = dummy;
    ListNode second = dummy;
    // Advances first pointer so that the gap between first and second is n nodes apart
    for (int i = 1; i <= n + 1; i++) {
        first = first.next;
    }
    // Move first to the end, maintaining the gap
    while (first != null) {
        first = first.next;
        second = second.next;
    }
    second.next = second.next.next;
    return dummy.next;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值