链表基础之删除链表的倒数第N个节点

首先一般思路,双指针法后续发布

删除倒数第N个节点,就是删除指定索引处节点的变体,这个指定索引index=链表长度-N;所以思路就是先求出链表长度,然后在指定索引处删除节点;

代码与注释如下:

复制代码
public class p19 {
    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 4, 5};/*leetcode题中的数组*/
        ListNode head = createLinkedList(arr);/*转化为链表*/
        ListNode listNode = removeNthFromEnd(head, 1);/*调用题目要求的方法*/
        printLinkedList(listNode);/*打印输出是否满足要求*/
    }

    //    1.把数组中的元素存入链表结构中,必须有构造函数
    public static ListNode createLinkedList(int[] arr) {//将输入的数组输入到链表中
        if (arr.length == 0) {
            return null;
        }
        ListNode head = new ListNode(arr[0]);
        ListNode current = head;
        for (int i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }

    //    2.打印结果测试
    public static void printLinkedList(ListNode head) {//将链表结果打印
        ListNode current = head;
        while (current != null) {
            System.out.printf("%d -> ", current.val);
            current = current.next;
        }
        System.out.println("NULL");
    }

    //      3.题目要求测试
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int count = 0;
        ListNode con = head;
        while (con != null) {
            con = con.next;
            count++;/*计算链表长度*/
        }
        int index = count - n;/*索引index就是长度-n*/
        ListNode dummy = new ListNode(0);/*新增一个虚拟头节点,为了方便,不需要讨论删除头节点的问题*/
        dummy.next = head;/*指向头节点*/
        ListNode cur = dummy;
        for (int i = 0; i < index; i++) {
            cur = cur.next;/*循环结束后,此时cur节点位于要删除节点的前一个节点*/
        }
        cur.next = cur.next.next;/*令cur指向下下个节点,跳过并删除节点*/
        return dummy.next;/*返回head节点*/
    }
}
复制代码

 

posted @   学习没什么用  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示