public 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做一个测试方法内容:public static void main(String[] args) {\n // Create a linked list with elements 1->2->3->4->5\n ListNodeE node5 = new ListNodeE(5);\n ListNodeE node4 = new ListNodeE(4, node5);\n ListNodeE node3 = new ListNodeE(3, node4);\n ListNodeE node2 = new ListNodeE(2, node3);\n ListNodeE node1 = new ListNodeE(1, node2);\n \n // Create an instance of the class\n Solution solution = new Solution();\n \n // Test the remove method\n ListNodeE result = solution.remove(node1, 2);\n \n // Print the updated linked list\n ListNodeE current = result;\n while (current != null) {\n System.out.println(current.val);\n current = current.next;\n }\n}

Java 中删除链表中第 k 个节点的代码示例

原文地址: https://www.cveoy.top/t/topic/pZuo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录