簡體   English   中英

如何將節點鏈表中的搜索值移動到鏈表的頭部?

[英]How to move a searched value in a linked list of nodes to the head of the linked list?

我正在嘗試編寫一個find(Object x)方法,如果找到一個存儲Object y.equals(x)的節點,將該節點移動到鏈表(自組織列表)的前面。 如果找到,該方法返回移到前面的節點的值。 如果沒有找到,返回null。

我的節點內部類包含一個Node<T> next和一個Object val

這是我嘗試過的:

public Object find(Object x) {

        //cant find an object that doesnt exist
        if (isEmpty()) {
            return null;
        }

        // store the head
        Node tmp = head;
        //keep track of previous for updating the link if found
        Node prev = null;


        //traverse linked list
        while (tmp!=null) {
            //find x
            if (tmp.val.equals(x)) {
                //update node storing x to be the head
                tmp = head;

                //re-link the LL
                prev.next = tmp.next;

                return head.val;
            }
            //continue traversing if not found
            prev = tmp;
            tmp = tmp.next;
        }
        //x was not found, return null;
      return null;
    } // end find

我的方法是沒有正確地找到對象,但目前我似乎找不到代碼有什么問題。 我是否需要以相反的順序遍歷鏈表才能做到這一點?

if塊沒有正確地重新連接您的列表。 tmp = head不會移動一個節點成為頭。 丟失了tmp引用的任何內容。 你應該改變tmp (而不是分配給它)並表明它的繼任者將是當前的head 然后你應該把它提升為head

    if (tmp.val.equals(x)) {
        // Only change something when the match is not the current head
        if (prev != null) { 
            // First(!) re-link the LL
            prev.next = tmp.next;
            // Move the node before the current head
            tmp.next = head;
            // Finally, make it the head
            head = temp;
        }
        return head.val;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM