簡體   English   中英

反轉與頭節點的鏈表

[英]reversing a linked list with the head node

好吧,似乎我正陷入無限循環,試圖反轉此列表。 所以說我有一些隨機數,例如4,5,6,7,而我試圖將其反轉為7,6,5,4。 我從頭上的節點開始,然后將其添加到最后一個節點的末端,直到獲得最終列表(IE 7,4-> 7,5,4,),但是我嘗試的所有操作都給了我無限循環。

    public void Reversing() {
    Node<E> currently = this.head;//set it to head to loo[
    Node<E> last = this.head;
    Node<E> temp = this.head; //not used anymore

    last=lastNode();//gets the last item in the list

    while (currently != null) {//loop until not null
        last.next=currently;
        currently=currently.next;

        if(last.info==currently.info){//break out of loop
            break;
        }  
    }
}

您正在反轉一個單鏈列表。 看到這個SO問題,該問題顯示了如何執行反向單鏈列表Java

我將復制答案:

Node<E> reversedPart = null;
Node<E> current = head;
while (current != null) {
    Node<E> next = current.next;
    current.next = reversedPart;
    reversedPart = current;
    current = next;
}
head = reversedPart;

暫無
暫無

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

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