Java 链表删除倒数第 k 个节点示例代码 - 完整主函数实现
以下是基于给定代码的主函数实现:\n\njava\npublic static void main(String[] args) {\n // 创建一个示例链表\n int[] arr = {1, 2, 3, 4, 5};\n ListNodeE head = buildLinkedList(arr);\n \n // 删除倒数第k个节点\n int k = 2;\n ListNodeE newHead = remove(head, k);\n \n // 打印删除节点后的链表\n ListNodeE curr = newHead;\n while (curr != null) {\n System.out.print(curr.val + " ");\n curr = curr.next;\n }\n}\n\npublic static ListNodeE remove(ListNodeE head, int k) {\n ListNodeE dummy = new ListNodeE(0);//定义一个虚拟头节点\n dummy.next = head;\n ListNodeE front = dummy, behind = dummy;\n while (front != null && k > 0) {\n front = front.next;\n k--;\n }\n while (front != null) {\n front = front.next;\n behind = behind.next;\n }\n behind.next = behind.next.next;\n return dummy.next;\n}\n\npublic static ListNodeE buildLinkedList(int[] arr){\n ListNodeE dummy = new ListNodeE(0);//虚拟头节点\n ListNodeE curr = dummy;\n for (int nums : arr) {\n curr.next = new ListNodeE(nums);\n curr = curr.next;\n }\n return dummy.next;\n}\n\n\n请注意,在上述代码中,我将 remove 和 buildLinkedList 方法都声明为 static 方法,以便在主函数中直接调用。
原文地址: https://www.cveoy.top/t/topic/pZ7Q 著作权归作者所有。请勿转载和采集!