I need to make a method that removes the last element of a LinkedList using recursion. This is what I have so far but it doesn't seem to be removing the node...when i call list.size() it is still the same size with the same values. What am I doing wrong here? This is for Java by the way
public void removeLastElement(Node curr){
if (curr == null)
return;
else{
if(curr.next == null)
curr = null;
else
removeLastElement(curr.next);
}
}
4 Answers 4
In a LinkedList to remove the last element you have to get the penultimate element and set
curr.next = null
-
how would i write that? i'm new to linked lists and recursion. sorry :(user1267952– user126795203/14/2012 05:16:02Commented Mar 14, 2012 at 5:16
-
@Ruuhkis add the "@" before the name so people could receive the comment in their inbox :)Luiggi Mendoza– Luiggi Mendoza03/14/2012 06:43:01Commented Mar 14, 2012 at 6:43
You're in the right way to get the recurrent function to remove the last node. The problem is you're identifying the penultimate node with curr.next == null
, if you got it, you nullify it, but that's your actual input! So, you must check if the actual node is the antepenultimate node on the list:
if (curr.next.next == null) {
curr.next = null; //Now you're modifying the data in your input.
}
With this change, there are more basic cases to check, but that's up to you, my friend.
-
antepenultimate: I assume you mean 3rd last?mikek3332002– mikek333200203/23/2012 02:06:35Commented Mar 23, 2012 at 2:06
-
@mikek3332002 yes that's what I meanLuiggi Mendoza– Luiggi Mendoza03/23/2012 02:20:13Commented Mar 23, 2012 at 2:20
Boolean deleteLast(Node n)
{
if(n.next == null)
return true;
if(deleteLast(n.next))
{
n.next = null;
return false;
}
return false;
}
Node deleteLast(Node n) {
if (n.next == null)
return null;
n.next = deleteLast(n.next);
return this;
}
The general idea is you ask the next node "hey, can you tell me where you are, and delete your last node?" The last node can then just say "I'm nowhere" and it'll all fall into place.
This is very similar to Aadi's answer, just using Node
s instead of boolean
s.
curr=curr.next
beforeremoveLastElement(curr.next);
..!!..and then change the last statement to :removeLastElement(curr);