簡體   English   中英

Java鏈表-如何復制數據?

[英]Java linkedlist - How to copy data?

我正在嘗試編寫一個函數,該函數將雙鏈表中的“ n”個節點從前面移到后面,並將它們添加到后面:

public class PetList {
    protected class LinkNode {
        protected LinkNode next;
        protected LinkNode prev;
        protected Pet animal; // note that my data within a node is an object

        public LinkNode() {
            next = prev = null;
        }
    }
    protected LinkNode first;
    protected LinkNode last;

    public PetList() {
        first = last = null;
    }
//...
//... other functions

public void Rotate(int n) {

}

現在,我知道如何在后面插入節點,例如:

public void insertRear(Pet giraffe) {
    LinkNode temp = new LinkNode();
    temp.animal = new Pet(giraffe);
    if(first == null) {
        first = last = temp;
        return;
    }
    temp.prev = last;
    last.next = temp;
    last = temp;
}

但是在我的旋轉功能中:

public void Rotate(int n)

我沒有對象作為參數。 也就是說,如何創建臨時LinkNode並將數據復制到第一個LinkNode的對象中,然后將我的臨時Node移到后面,刪除我的第一個節點? 還是有另一種更好的方法? 謝謝你的幫助。

它應該很簡單。 這是從頭到尾移動一個節點的方法:

public void moveHeadToTail() {
    if (first == null || last == null) {
        throw new IllegalStateException("can't do that on empty list");
    }
    // Detach the first node
    LinkNode temp = first;
    first = temp.next;
    first.previous = null;
    temp.next = null;

    // Put the tmp node at the end
    last.next = temp;
    temp.prev = last;
    last = temp;
}

然后,您可以將其拆分為更好的功能: popHeadpushTail

public LinkNode popHead() {
    if (first == null) {
        throw new IllegalStateException("can't do that on empty list");
    }
    LinkNode temp = first;
    first = temp.next;
    first.previous = null;
    temp.next = null;
    return temp;
}

public void pushTail(LinkNode node) {
    if (last == null) {
        throw new IllegalStateException("can't do that on empty list");
    }
    last.next = node;
    node.prev = last;
    node.next = null;
    last = node;
}

然后,這使旋轉更容易:

public void moveHeadToTail() {
    pushTail(popHead());
}

然后,使它適用於n的修改應該是微不足道的。

我將從列表的開頭切掉一個長度為n節點,同時跟蹤切出列表中的第一個和最后一個節點。 first設置到切碎的子列表之后的節點,使其成為新的第一個節點。 然后,通過在子列表中舊的最后一個節點與第一個節點之間提供雙向鏈接,將子列表追加到末尾。 最后將last設置到子列表的末尾,然后就可以完成了。

將節點繪制為紙上的框,並將鏈接繪制為指向其他框的箭頭。 擦除並繪制以可視化這些步驟。 然后,一切都應該更加清楚。

暫無
暫無

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

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