反向链接列表递归

时间:2017-09-19 15:59:29

标签: java recursion linked-list

我已经通过我的代码跟踪使用递归来反转链接列表,我找不到任何错误,但我知道它不起作用。有人可以解释一下原因吗?

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    Personal_id int,
    PRIMARY KEY (OrderID),
    CONSTRAINT FK_PersonOrder FOREIGN KEY (Personal_id)
    REFERENCES Persons(Personal_id)
);

2 个答案:

答案 0 :(得分:1)

以下是您的代码的工作版本,添加了一些帮助结构:

class LList {
    Node head;

    void reverse() {
        head = rev(head, head.next);
    }

    private Node rev(Node node, Node next) {
        if(next == null)    return node; //return the node as head, if it hasn't got a next pointer.
        if(node == this.head)   node.next = null; //set the pointer of current head to null.

        Node temp = next.next;
        next.next = node; //reverse the pointer of node and next.
        return rev(next, temp); //reverse pointer of next node and its next.
    }
}

class Node {
    int val;
    Node next;
    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }
}

答案 1 :(得分:0)

您需要在切换之前调用reverseLL(head.next),以遍历列表并从最后一个节点向上开始。这需要进行一些更改。