LeetCode- 19 删除链表的倒数第N个节点
题目地址
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
参考实现
/** * 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; } * } */ /** * 通过链表长度 进行处理 * * @param head * @param n * @return */ public static ListNode removeNthFromEnd1(ListNode head, int n) { ListNode dumny = new ListNode(0, head); ListNode current = dumny; for (int i = 1; i < getLenth1(head) - n + 1; i++) { current = current.next; } //执行删除 current.next = current.next.next; return dumny.next; } /** * 获取链表大小 * * @param head * @return */ public static int getLenth1(ListNode head) { int length = 0; while (head != null) { head = head.next; length++; } return length; } /** * 利用栈特性处理 * * @param head * @param n * @return */ public static ListNode removeNthFromEnd(ListNode head, int n) { ListNode dumny = new ListNode(0, head); Deque<ListNode> stack = (Deque<ListNode>) new LinkedList<ListNode>(); ListNode current = dumny; while (current != null) { stack.push(current); current = current.next; } for (int i = 0; i < n; i++) { stack.pop(); } ListNode peek = stack.peek(); peek.next = peek.next.next; return dumny.next; } /** * 双指针处理 * * @param head * @param n * @return */ public static ListNode removeNthFromEnd3(ListNode head, int n) { ListNode dummy = new ListNode(0, head); ListNode first = head; ListNode second = dummy; for (int i = 0; i < n; i++) { first = first.next; } while (first != null) { first = first.next; second = second.next; } second.next = second.next.next; return dummy.next; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
2023-04-17 面向对象编程概述