每日一练_45(2021.7.24) 删除链表的第N个结点(LeetCode)。

本文讲解了如何使用Java实现LeetCode中的删除链表倒数第N个节点问题,通过ListNode类实现链表操作,包括添加节点、获取链表长度和删除指定位置节点。示例代码详细展示了整个过程,适合初学者理解链表操作技巧。

老规矩,官方代码:作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode) 

个人微改:
import java.util.*;
class ListNode{
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val){this.val=val;}
    ListNode(int val,ListNode next){this.val = val;this.next=next;}
    
    public void addNode(int e) {
        ListNode newNode = new ListNode(e);
        if(this.next==null) {
            this.next = newNode;
        }else {
            this.next.addNode(e);
        }
    }
    
    public ListNode remove(ListNode head,int n) {
        ListNode rookie = new ListNode(0,head);
        int length = getLength(head);
        ListNode cur = rookie;
        for(int i=1;i<length-n+1;i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        ListNode ans = rookie.next;
        return ans;
    }
    public int getLength(ListNode head) {
        int length = 0;
        while(head!=null) {
            ++length;
            head = head.next;
        }
        return length;
    }
    public void print() {
        System.out.print(this.val);
        if(this.next!=null) {
            System.out.print("-->");
            this.next.print();
        }
    }
}
public class deleteLinkList {
    public static void main(String args[]) {
        ListNode L1 = new ListNode();
        System.out.println("please enter the linked list capacity :");
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int a[] = new int[m];
        System.out.println("please enter the data of your linked list :");
        for(int i=0;i<m;i++) {
            a[i]=sc.nextInt();
            L1.addNode(a[i]);
        }
        System.out.println("please enter the number of reciprocal of the list you want to delete :");
        int n = sc.nextInt();
        L1.remove(L1.next,n);
        L1.next.print();
        sc.close();
        
    }
}
测试结果:

please enter the linked list capacity :
5
please enter the data of your linked list :
1 2 3 4 5
please enter the number of reciprocal of the list you want to delete :
2
1-->2-->3-->5

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值