Recursion using Linked List Java

Soldato
Joined
15 Aug 2010
Posts
8,780
Location
N. Ireland
Hi all, I am having a bit of trouble with a method to insert a char value in front of a specific char value using recursion.

Here's my recursive and wrapper methods
Code:
    /*
     * recursive method for inserting
     */
    public Csc2001Node insertBefore(char c, Csc2001Node head, char toInsert)
    {   
        if(head==null){
            return head = new Csc2001Node(toInsert);
        }        
        else if (head.next!=null && head.ch == c || head.ch == c) 
        {
            Csc2001Node nextNode = head.next;
            head.next = new Csc2001Node(toInsert);
            head.next.next = nextNode;
        }
         else
            head.next = insertBefore (c, head.next, toInsert);

         return head;
    }
    /*
     * wrapper method for inserting
     */
    public void insertBefore(char c, char toInsert){
        head = insertBefore(c, head, toInsert);
    }

This is a piece of code from my tester class which adds a character in front of a specific character.
Code:
		System.out.println("Trying to insert V before e into the front of the list and printing out the list");
		mylist.insertBefore('e', 'V');
		mylist.recursePrintList();

The output should be
Trying to insert Z before p, a character that does not exist in the list, and
printing out the list
V e a Y s t e r Z

But my method outputs
Trying to insert Z before p, a character that does not exist in the list, and printing out the list
eVaYsterZ

Notice how the V is outplace by one character.

Anyone shine a light on what Im doing wrong with my recursive method?

Thanks
 
Soldato
OP
Joined
15 Aug 2010
Posts
8,780
Location
N. Ireland
I have actually been spending half of the day looking through stackoverflow and google :p

Tried implementing a couple of the "solutions" but non have given me the right output for some reason :confused:

What I have is the closest I can get to the correct output.
 
Last edited:
Back
Top Bottom