在java中反向链表

时间:2015-06-08 18:14:17

标签: java pointers data-structures linked-list

我想知道这是否是一个有效的递归解决方案,是否可以进行任何改进。我已经用一些输入测试了这个解决方案,它似乎有效。

public Node reverse(Node head) {

if(head == null) {
    return null;
}

if (head.next == null) {
    this.head = head;
    return head;
}

Node n = head.next;
head.next = null;   

reverse(n).next = head; 

return head;
}

谢谢。

1 个答案:

答案 0 :(得分:1)

就算法而言,我认为这种方法可以满足你的需要,我相信你想要一个链表

A-> B-&以及c

转换为

C-> B-> A,并返回A.

我只是对这个方法的范围有点困惑,它是Node的实例方法吗? “这个”在第8行。

我不确定的一件事是,如果你没有保留其他指向C和B的指针,在反向完成之后,你会留下列表C-> B-> A,返回指针到A.看起来C和B没有任何变量指向,它不会被垃圾收集?并删除?也许这个问题是通过“这个”问题解决的。

构建列表的一个好方法应该是返回列表头部的方法。但是你的方法会返回尾部。 我建议将它设为Node的实例方法,然后使用head调用reverse()方法,并返回新的头

public Node reverse() {

    if (this.next == null) {    
        return this;
    }

    Node n = this.next;
    Node newhead=n.reverse()  // After reverse, n should be at the tail 
    n.next = this; 

    return newhead;
}

类似这样的东西,但我还没有测试过代码