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

1、题目链接

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

2、分析

设置了一个虚拟头结点,可以有效的避免删除头结点等一些边界情况。

cur = dummy; //赋值为虚拟头结点,关键

3、上代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || n <= 0) return null;
       
        ListNode dummy = new ListNode(-1); //设置一个虚拟头结点,可以避免一些特殊情况
        dummy.next = head;

        ListNode cur = head;

        int length = 0;
        while(cur != null) {
            length ++;
            cur = cur.next;           
        }

        cur = dummy; //赋值为虚拟头结点,关键
        int target = length - n;
        while(target > 0) {
            cur = cur.next;
            target --;
        }
        cur.next = cur.next.next;
        
        return dummy.next;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值