簡體   English   中英

反轉單個鏈表

[英]Reversing single 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我有一個周期。 如何解決?

您只反轉列表,所以我不知道您為什么要對“ this”對象執行某些操作。 無論如何,我認為您應該只使用它: https : //www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/api/list/MutableList.html#reverseThis--

我將使用遞歸,如下所示:

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

您的代碼的問題是,您永遠不會為next賦值。 這是我對您的問題的迭代解決方案。 另外,為了使自己更輕松,我建議您使用一個引用鏈接列表開頭的標題。

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