2013-04-06 158 views
0

我有一個單鏈表,我只想刪除該列表的最後一個元素。我檢查了它,但它不起作用。我不知道爲什麼。刪除單鏈表的最後一個元素不起作用

看看我的代碼(PS我想遞歸溶液):

// Delete Last Element 
public void deleteLast(){ 

    if(head == null){ 
     return; 
    } 

    if(head.next == null){ 
     head = null; 

    }else{ 
     deleteLast(head.next); 
    } 
} 

private void deleteLast(ListElement head){ 

    if(head == null){ 
     return; 
    } 

    if(head.next == null){ 
     head = null; 
    }else{ 
     deleteLast(head.next); 
    } 
} 
+0

語言? Java的? – Dukeling 2013-04-06 19:16:08

回答

1

head = null只是將本地head變量null,而不是它的引用鏈接列表中的對象,您需要這樣做:

private void deleteLast(ListElement head) 
{ 
    if (head.next.next == null) 
     head.next = null; 
    else 
     deleteLast(head.next); 
} 

你會發現我也刪除您if (head == null)檢查,我相信它不是必需的。

編輯:另一種方式來做到這一點:

// returns whether we should delete the passed in parameter 
private boolean deleteLast(ListElement head) 
{ 
    if (head.next == null) 
     return true; 
    else if (deleteLast(head.next)) 
     head.next = null; 
    return false; 
} 
+0

天哪,它的作品xD ...真棒!多謝。但是如果沒有next.next,沒有辦法做到這一點嗎?我不喜歡它的外觀:P – user2252902 2013-04-06 19:42:39

+0

@ user2252902請參閱編輯。 – Dukeling 2013-04-06 19:54:49

+0

哦,我喜歡第二種方式,非常感謝你;-) – user2252902 2013-04-06 20:36:52

相關問題