当代码已经定义好了一个类和一个方法,需要写一个主函数来测试这个方法的功能。以下是一个示例主函数的实现:

public class Main {
    public static void main(String[] args) {
        // 创建一个链表
        ListNodeE node1 = new ListNodeE(1);
        ListNodeE node2 = new ListNodeE(2);
        ListNodeE node3 = new ListNodeE(3);
        ListNodeE node4 = new ListNodeE(4);
        ListNodeE node5 = new ListNodeE(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        // 打印原始链表
        System.out.println("原始链表:");
        printList(node1);

        // 调用remove方法删除指定位置的节点
        ListNodeE newHead = remove(node1, 2);

        // 打印删除节点后的链表
        System.out.println("删除节点后的链表:");
        printList(newHead);
    }

    public static ListNodeE remove(ListNodeE head, int k) {
        ListNodeE dummy = new ListNodeE(0);
        dummy.next = head;
        ListNodeE front = dummy, behind = dummy;
        while (front != null && k > 0) {
            front = front.next;
            k--;
        }
        while (front != null) {
            front = front.next;
            behind = behind.next;
        }
        behind.next = behind.next.next;
        return dummy.next;
    }

    public static void printList(ListNodeE head) {
        ListNodeE current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }
}

在主函数中,首先创建了一个链表,并打印出原始链表。然后调用remove方法删除指定位置的节点,并打印删除节点后的链表。最后,定义了一个辅助函数printList来打印链表的元素

您能帮我基于这段代码写一个主函数吗谢谢您改天送您所需! public class ListNodeE int val; ListNodeE next; public ListNodeEint x val = x; public ListNodeE removeListNodeE head in

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

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