A recursive traversal of a linked list usually looks like a look, if you are at the end of the list (you have a null link), and if not, then do something with a recursive call to the next list item, and if you do, do the basic case. Assuming the nodes look like this from the outside:
public class Node{ public Node getNext(); public String toString(); }
... your method looks like this (inside the class that you use to run it):
public String concatList(Node head){ if(head == null){ return ""; //empty list is a null pointer: return empty string } return head.toString() + concatList(head.getNext()); }
The end of the list or no list at all looks the same β a null pointer β and returns an empty string, as indicated; everything else takes the current node and combines it into a list created by getting a concatenated version of the rest of the string.
Be careful: if something messes up your list, so this is actually a loop, there are no checks for this and it will work forever until the stack memory runs out, unless Java detects loop optimization of this recursive function, and just will run forever.
source share