简体   繁体   English

反转单个链表

[英]Reversing single linked list

I tried to revert single linkied list as follows: 我尝试还原单个链接列表,如下所示:

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;
        }
    }

But this implementation does not work. 但是此实现无效。 When I assign to this I got a cycle. 当我分配到this我有一个周期。 How to fix it? 如何解决?

You are reversing only the list, so I don't know why do you want to do something with "this" object. 您只反转列表,所以我不知道您为什么要对“ this”对象执行某些操作。 Anyway I think you should just use this: https://www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/api/list/MutableList.html#reverseThis-- 无论如何,我认为您应该只使用它: https : //www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/api/list/MutableList.html#reverseThis--

I would use recursion, like this: 我将使用递归,如下所示:

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

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

You will need to call reverse to the head of your list. 您将需要反向调用到列表的开头。 As about your concrete problem, you are changing the next before you get a chance to use it. 关于您的具体问题,在有机会使用它之前,您正在更改下一个。 You might want to do something like this instead: 您可能想要执行以下操作:

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;
    }
}

Your code's problem is that you never assign a value to next. 您的代码的问题是,您永远不会为next赋值。 Here's my iterative solution to your problem. 这是我对您的问题的迭代解决方案。 Also, to make it easier on yourself I would suggested having a head that references the beginning of your linked list. 另外,为了使自己更轻松,我建议您使用一个引用链接列表开头的标题。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM