如何使用 void 方法递归反转链表?

How can I recursively invert a linked list with a void method?

我在使用 void 方法反转链表时遇到问题。我只允许使用两个指针节点 (p, q)。我找到了几种方法,但没有一个是无效的。我需要自己修改根列表(这就是为什么它必须是无效方法)。该方法必须是递归的(我知道 void 方法中的基本定义不同)。这是我到目前为止所做的(不多)。

public方法:

public void reverse(){
        reverse(first, null);
    }

私有方法:

private void reverse(Node p, Node q){
    if(p.next!=null)
        reverse(p.next,p);
    p.next=q;
}

您的代码运行良好!您可能只是没有正确测试它。以下是我的测试方式:

public static void main(String[] args) {
    Node last = new Node(4, null);
    Node first = new Node(1, new Node(2, new Node(3, last)));

    System.out.println("before: " + first);
    Node.reverse(first);
    System.out.println("after: " + last);
}

private static class Node {
    private int val;
    private Node next;
    public Node(int v, Node n) { val = v; next = n; }
    public String toString() { return val + (next == null ? "" : " -> " + next); }

    public static void reverse(Node first) {
        reverse(first, null);
    }
    private static void reverse(Node p, Node q) {
        if (p.next != null)
            reverse(p.next, p);
        p.next = q;
    }
}

输出

before: 1 -> 2 -> 3 -> 4
after: 4 -> 3 -> 2 -> 1

编辑:为避免在调用代码中需要 last,添加方法 getLast() 以便您的 public reverse 可以 return 反转完成后就可以了。由于 Java 只是按值传递,因此您无法从方法 reverse 内部更改调用者 first 的值。进行以下更改:

// in Node
private Node getLast() { return next == null ? this : next.getLast(); }
public static Node reverse(Node first) {
    Node last = first.getLast();
    reverse(first, null);
    return last;
}

// in main()
System.out.println("before: " + first);
first = Node.reverse(first); // update the value of first afterwards
System.out.println("after: " + first);