Home > Software design >  How to add a item at the last in the list by recursion?
How to add a item at the last in the list by recursion?

Time:02-22

public class SLList {

    public class IntNode {
        public int item;
        public IntNode next;
        public IntNode(int i, IntNode n){
            item = i;
            next = n;
        }
    }

    public IntNode first;

    public SLList(int x){
        first = new IntNode(x,null);
    }

    public void addFirst(int x){
        first = new IntNode(x, first);
    }

    public int getfirst(){
        return first.item;
    }
    
    public void addLast(int x) {
    
    }
    
    public static void  main(String[] args){
        SLList L =  new SLList(10);
        L.addFirst(5);
        L.addFirst(8);
        L.addLast(9);
        System.out.println(L.getfirst());
    }
}

How to add an item at the last in the list using recursion? I want to add the last of the list by recursion but am not able to do so as I go through the pointer is pointing at the last element so it's returning the element added and the last element and not the whole list.

CodePudding user response:

When designing a recursive method you need to implement two parts:

  • base case that represents an input for which it's clear the expected output will be. In your case, the last node is a node that doesn't point to any other node, i.e. its next field is null. Also as a precaution, we need to address the situation when the given node is null before accessing its next field.
  • recursive case - is a part recursive calls happen and main logic of the method resides. For this task, the recursive case is fairly simple: if the current node isn't null and it points to the non-null node, then the next node should be returned.

In order to add a new last node firstly we need to find a reference to the existing one.

That's how the recursive method that yields the last node might look like:

    public IntNode getLast(IntNode curNode) {
        if (curNode == null) {
            return null;
        }
        if (curNode.next == null) {
            return curNode;
        }

        return curNode.next;
    }

Note, that getLast() can return a null. That means that field first is null and we can delegate to job to the method addFirst(). Otherwise, the new instance of the node will be created and assigned to last.next.

    public void addLast(int x) {
        IntNode last = getLast(first);
        if (last == null) {
            addFirst(x);
        } else {
            last.next = new IntNode(x, null);
        }
    }
  • Related