簡體   English   中英

嘗試刪除單循環鏈接列表中的節點

[英]Trying to delete a node in Singly Circular Linked List

我正在嘗試刪除具有給定鍵的節點,並且還想顯示更新的Tail和Head節點值。 我可以刪除第一個節點(頭),但不能刪除尾部節點,請檢查下面的代碼

public void delete(int key){
        Node current = head;            
        while(current.next.data != key){
            current = current.next;
        }
        if(current.next.data == key ){              //deleting current node
            current.next = current.next.next;
            if(current.next == head)
                tail = current;
            else if(current == head)
                head = current.next;    
        }
    }

我的主要方法:

public class Caller {
    public static void main(String args[]){

            Linklist theList = new Linklist();  
            theList.insertFirst(22);
            theList.insertFirst(44);
            theList.insertFirst(55);
            theList.insertFirst(66);
            theList.delete(22);
            System.out.println("deleting 22");
            theList.display();
            theList.delete(66);
            System.out.println("Deleting 66");
            theList.insertLast(99);
            theList.insertLast(11);
            theList.display();
    }
}

我的insertLast方法:

public void insertLast(int data){
        Node newNode = new Node(data);
        Node current = head;

        while(current.next != head){
            current = current.next;
        }

        current.next = newNode;
        newNode.next = head;
        tail = newNode;
    }

我的輸出是:

deleting 22
Displaying list first ----> last
{ 66 }
{ 55 }
{ 44 }
Head : 66 Tail: 44
Deleting 66

此代碼后無任何反應

這是通過用筆和紙逐步執行算法可以最好地解決的問題之一。 我認為問題不在於刪除尾部節點(您自己的日志輸出顯示該節點正在工作),而是在於刪除頭節點(在這種情況下為“ 66”)。 是的,最后插入的是“ 66”,但它已插入列表中其他所有對象的前面,因此成為頭節點。

問題是在更新頭/尾指針之前,您要更改循環列表的結構。 在刪除頭節點的情況下,當代碼到達current.next = current.next.next; 線, current指向尾節點, current.next是頭節點, current.next.next是頭+1節點。 通過執行分配, current.next指向head + 1節點,這意味着if(current.next == head)else if (current == head)都不會觸發。 頭節點現在在循環列表之外,但是head指針仍然指向該節點。 更糟糕的是, head.next仍然指向循環列表。

還有兩個問題:

  • 重要:delete()方法無法處理列表最后一個元素的刪除
  • 次要的: if(current.next.data == key )是不必要的,因為它實際上是前一個while循環的停止條件。

我一直跟蹤先前和當前的節點,並且它起作用了!

public void delete(int key){
    Node current = head;
    Node prev = current;

    while(current.data != key){
        prev = current;
        current = current.next;
    }
    if(current.data == key ){              //deleting current node
        if(current == head){
            prev = tail;
            head = current.next;
        }else if(current == tail){
            tail = prev;
            head = current.next;
        }   
    prev.next = current.next;   

    }

}

暫無
暫無

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

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