2016-05-18 34 views
-1

給定一個循環鏈表在Java中編寫一個方法來刪除一個節點。如何從Java中的循環鏈表中刪除一個節點?

+0

歡迎的StackOverflow!我們不會爲你寫代碼!我們想幫助你,但如果你不努力,我們也不會。 – SZenC

+0

因爲我沒有找到我要找的東西,所以我在做一個問題和回答的事情。顯然我沒有做對。 –

回答

-1

真的有四種情況需要考慮。

案例1:

是列表是空的?如果這樣返回null或返回

案例2:

只有一個列表中的元素。 將指針設置爲空,並將列表設置爲空。

案例3:

刪除的東西在列表的前面。 在這種情況下,我們有幾個步驟。

步驟:

  1. 創建一個臨時指針列表。
  2. 移至列表末尾。
  3. 將溫度指針設置爲列表的前面。
  4. 向前移動列表的前端。
  5. 將temp的指針設置爲null。
  6. 將列表的末尾設置爲指向列表的新前端。

案例4:這種格式1-> 2-> 3->當我們刪除中間項

刪除的東西。 備註。這適用於刪除的最後一個項目,以及因爲它循環回一圈爲1

步驟

  1. 做一個臨時的指針列表。
  2. 向前移動臨時指針,直到找到要刪除的數據。
  3. 製作刪除節點(示例節點刪除)並將其設置爲temp的指針。
  4. 設置temp跳過我們正在刪除的節點。
  5. 將刪除節點的指針設置爲空。

    public void delete(int data) { 
        // Null list case 
        if(list == null) return; 
    
        // Delete the only element case 
        if(list.data == data && list.next.data == list.data) { 
         list.next = null; 
         list = null; 
         return; 
        } 
    
        // Delete the front of the list case 
        if(list.data == data) { 
    
         // Move to the end of the list 
         Node end = list; 
         while(end.next.data != list.data) { 
          end = end.next; 
         } 
    
         Node temp = list; 
         list = list.next; 
         temp.next = null; 
         end.next = list; 
         return; 
        } 
    
        // Delete something in the middle 
        Node temp = list; 
        while(temp.next.data != data && temp.next.data != list.data) { 
         temp = temp.next; 
        } 
    
        // We circled the list and did not find the element to delete  
        if(temp.next.data == list.data) return; 
    
        Node del = temp.next; 
        temp.next = temp.next.next; 
        del.next = null; 
    } 
    
+0

OP要求一種方法來刪除一個'Node',然而在這個方法中,你提供了一個方法來刪除一個Node的內容與'int'匹配的節點。這也假定在圓形鏈表中只有唯一的元素。 –

+0

這是OP,我認爲他只是把他的代碼發佈到了地獄 – sbowde4

+0

這似乎過於複雜。你真的關心除了 - 我繞過嗎?除此之外,你只是刪除一個節點;沒有? – ChiefTwoPencils