这种反向链接列表的方法是否存在问题

时间:2018-06-24 20:41:48

标签: java recursion linked-list

public static Node reverse(Node curr, Node ogHead) {
    // base case if we end up back at the head of the original list return
    // our new list
    if (curr == ogHead) {
        return ogHead;
    }

    // ogHead is initiall setup to be the tail of curr now the current node
    // of curr is added to ogHead
    ogHead.addNodeAfter(curr.getData());

    // set the curr node equal to the next node in the list
    curr = curr.getLink();
    // call the method again with the new current element and the updated
    // new list

    reverse(curr, ogHead);

    return ogHead;

}

我已经毕业了,但是我想知道这是否是反向链接列表的可接受方法。我相信我最初得到的反馈是,它可以奏效,但可以使其更易于测试。 curr参数i使用getTail()方法传递列表的头部,参数ogHead我传递列表的末尾。

2 个答案:

答案 0 :(得分:1)

我不能离开这个人。这是递归方法的一个更好的实现,其中节点只需四处移动即可完成逆转:

public static Node reverse(Node curr, Node ogHead) {
    // base case if we end up back at the head of the original list return
    // our new list

    if (curr == ogHead) {
        return ogHead;
    }

    Node oldOgHead = ogHead.link; // Remember what is behind (the original) ogHead
    Node nextCurr = curr.link; // Remember curr's successor (which is the starting point for the next recursion)

    // Move/insert curr right after ogHead
    ogHead.link = curr; // Put curr after ogHead
    curr.link = oldOgHead; // Whatever was after ogHead, put it after curr

    curr = nextCurr; // Prepare for next recursion

    if (curr != null) {
        reverse(curr, ogHead);
    }

    return ogHead;
}

不会浪费内存,只需更新引用即可。

答案 1 :(得分:0)

该代码可能有效。 addNodeAfter的实现方式完全取决于问题。也许您可以通过添加实现来更新问题。

如果是这样,假设您从ogHead开始遍历,您将获得相反的列表:

class Node {

    private Object data;
    private Node link;

    public Node(Object data, Node link) {
        this.data = data;
        this.link = link;
    }

    public void addNodeAfter(Object data) {
        link = new Node(data, link);
    }

}

但这仅是因为遍历链表时会创建新节点。原始链表仍将存在。因此,如果从列表1-> 2-> 3-> 4开始,现在将具有列表1-> 2-> 3-> 4-> 3-> 2-> 1,这可能不是您想要的。仅给addNodeAfter的数据部分时,我看不到任何其他实现Node的方法。