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

【JAVA】删除链表的倒数第N个节点,第1张

【JAVA】删除链表的倒数第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]
class Solution {
    public ListNode removeNthFromEnd(ListNode head,int n){
        int pos=length(head, n);
        if(pos==n)
            return head.next;
        return head;
    }

    public int length(ListNode node,int n){
        if(node==null) return 0;
        int pos=length(node.next,n)+1;
        if(pos==n+1)
            node.next=node.next.next;
        return pos;
    }
}
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode pre=head;
        int last=length(head)-n;
        if(last==0) return head.next;
        for(int i=0;i 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5712985.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存