-1

I need to recursively append a Node to a linked list, not sure why my code doesn't work

public void RecursiveAppend(Node example, Node add){
   if(example == null){
       example = add; 
   } else {
       RecursiveAppend(example.next, add);
   }
}

Method to print list

public void IterativeTraversal(){
       Node example = m_head;
       while(example != null){
           System.out.print(example.data + " ");
           example = example.next;
       }
   }
public class LinkedListDemo {
    public static void main (String [] args){
        LinkedList example = new LinkedList();
        Node A = new Node(10);
        Node B = new Node(30);
        Node C = new Node(50);
        Node D = new Node(70);
        example.append(A);
        example.append(B);
        example.append(C);
        example.RecursiveAppend(D);
        example.IterativeTraversal();
    }
}

Result: 10 30 50

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

You would want to check to see if example.next == null then set example.next to add instead of checking for example == null because if you need to be able to assign example.next and you can not do that if you have moved passed the node.

TobiSH
  • 2,833
  • 3
  • 23
  • 33
0

So null + 1 = null null * 1 = null similary you have set example to null in here

if(example == null){
  example = add; 
}

your base condition will be executed when there's a null value. so say you present node data is 40 and its next is null, So after 40 RecursiveAppend(example.next, add); this will make example as null and so Your base case hits if(example == null) and in there its example = add; which means null = add Which is null.
To over come this your base case should hit when the current node next has null like.

 if(example.next == null){
       example.next = add; 
   }

And this will solve the problem. Overall code

public void RecursiveAppend(Node example, Node add){
   if(example.next == null){
       example.next = add; 
   } else {
       RecursiveAppend(example.next, add);
   }
Swapnil Padaya
  • 687
  • 5
  • 14