Trying to create removeLastElement using recursion

I need to create a method that removes the last LinkedList element using recursion. This is what I have so far, but it doesn't seem to delete node ... when I call list.size (), it is all 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
source share
4 answers

In LinkedList, to remove the last item, you must get the penultimate item and set

 curr.next = null 
+1
source

You are the surest way to return the current function to remove the last node. The problem is that you identify the penultimate node with curr.next == null , if you received it, you invalidate it, but this is your actual input! So, you should check if the node antepenultimate node in the list is really:

 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 it is up to you, my friend.

+1
source
 Boolean deleteLast(Node n) { if(n.next == null) return true; if(deleteLast(n.next)) { n.next = null; return false; } return false; } 
0
source
 Node deleteLast(Node n) { if (n.next == null) return null; n.next = deleteLast(n.next); return this; } 

The general idea is to ask the next node "hey, can you tell me where you are and delete your last node?" The last node can simply say "I'm nowhere," and all this will fall into place.

This is very similar to Aadi's answer, just using Node instead of boolean s.

0
source

Source: https://habr.com/ru/post/1401301/


All Articles