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
This is a piece of code from my tester class which adds a character in front of a specific character.
The output should be
But my method outputs
Notice how the V is outplace by one character.
Anyone shine a light on what Im doing wrong with my recursive method?
Thanks
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