删除链表倒数第n个结点

方法一

  1. 首先求出整个链表的长度;
  2. 如果链表长度为给出的指定的位置,表明要删除的头结点;
  3. 然后用长度和给出的指定的位置求出要删除的位置;
public ListNode removeNthFromEnd(int n) {
        // 求长度
        int nums = 0;
        ListNode next = head;
        while (next != null) {
            nums++;
            next = next.next;
        }

        // 如果删除的是头结点
        if (n == nums) {
            return head.next;
        }
        // 否则
        int tar = nums - n - 1;
        int i = 0;
        ListNode front = head;
        ListNode behind = head.next;
        while (i < tar) {
            front = behind;
            behind = behind.next;
            i++;
        }
        front.next = behind.next;
        return head;
    }

方法二:双指针法

  1. 先让尾指针走n个位置;
  2. 然后将尾指针和头指针一起移动,直到尾指针指向最后一个结点;
  3. 这时头指针指向的结点的下一个结点就是要删除的结点;
// 双指针解决
    public ListNode removeNthFromEnd(int n) {
        ListNode front = head;
        ListNode behind = head;

        // 先让尾指针走n步
        for (int i = 0; i < n; i++) {
            behind = behind.next;
        }
        if (behind == null) { // 表明删除的头结点
            return head.next;
        }

        // 然后一起移动
        while (behind.next != null) {  // 这个判断条件可以保证behind最后一定是位于最后一个结点的
            behind = behind.next;
            front = front.next;
        }

        front.next = front.next.next;
        return head;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值