反转单个链表

时间:2017-03-31 07:13:40

标签: java linked-list

我尝试按如下方式恢复单个链接列表:

public class MutableLst<T> {
    public T current;
    public MutableLst<T> next;

    private MutableLst(T current){
        this.current = current;
    }

    public static <T> MutableLst<T> create(T current){
        return new MutableLst<T>(current);
    }

    public void reverse(){
        MutableLst<T> newNext = null;
        MutableLst<T> nxt = next;
        next = newNext;
        while(nxt != null) {
            newNext = this;  //<------- cycle is here
            current = nxt.current;
            next = newNext;
            nxt = nxt.next;
        }
    }

但是这种实现不起作用。当我分配给this时,我得到了一个周期。如何解决?

3 个答案:

答案 0 :(得分:2)

你只是在撤消列表,所以我不知道你为什么要用&#34;这个&#34;宾语。无论如何,我认为你应该使用这个: https://www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/api/list/MutableList.html#reverseThis--

答案 1 :(得分:0)

我会使用递归,如下所示:

public void reverse(MutableLst<T> previous){
    if (this.current.next !== null) {
        this.next.reverse(this);
    }
    this.next = previous;
}

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

您需要反向拨打列表的头部。至于你的具体问题,在你有机会使用之前,你正在改变下一个问题。你可能想做这样的事情:

public void reverse(){
    MutableLst<T> previous = null;
    MutableLst<T> currentItem = this;
    MutableLst<T> nxt = null;
    while(currentItem != null) {
        nxt = currentItem.next;
        currentItem.next = previous;
        previous = currentItem;
        currentItem = nxt;
    }
}

答案 2 :(得分:0)

您的代码的问题是您从未为下一个分配值。这是我对你的问题的迭代解决方案。另外,为了让自己更容易,我建议有一个引用链表开头的头。

public void reverse() {
    MutableLst<T> prev = null;
    MutableLst<T> curr = head;
    MutableLst<T> next = null;
       while (curr != null) {
           next = curr.next;
           curr.next = prev;
           prev = curr;
           curr = next;
       }
    }
    head = prev;