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

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

进阶:你能尝试使用一趟扫描实现吗?

示例 1:


输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:

输入:head = [1], n = 1
输出:[]
示例 3:

输入:head = [1,2], n = 1
输出:[1]
 

提示:

链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

思路:

1.暴力解法:首先我们经过一次遍历得到链表的长度count,可计算出需要删除第coune-n+1个元素,接着我们再进行遍历,将指针temp移动到需要删除元素的前一个元素进行删除(注意对首元素的删除特殊处理)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode temp = head;

        //存储链表长度
        int count = 0;
        while(temp!=null){
            temp = temp.next;
            count++;
        }
        //需要删除第几个元素
        n = count-n+1;
        if(n==1){
            return head.next;
        }
        int sum = 1;
        temp = head;
        while(sum<n-1){
            temp = temp.next;
            sum++;
        }
        temp.next = temp.next.next;
        return head;
    }
}


 

2.快慢指针法:我们可以让fast指针先走n步,紧接着让fast指针和slow指针同步移动,直到fast指针到链表末尾,这个时候slow指针恰好在需要删除元素的前一位,我们进行删除即可(同样需要对删除链表首元素进行特殊处理)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(n>0){
            fast = fast.next; 
            n = n-1;
        }
        if(fast==null){
            return head.next;
        }

        while(fast.next!=null){
            slow = slow.next;
            fast = fast.next;
        }

        slow.next = slow.next.next;

        return head;

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值