递归单链表插入之前方法切断列表的其余部分

Recursive Singly Linked List insert Before method cutting off rest of list

在使用递归方法创建手动链表时,我无法弄清楚为什么我的 Insert Before 方法在插入新节点后会切断链表。该列表未排序。我是新手,如能就此发生的原因提供任何帮助,我们将不胜感激。

我的节点class

class Csc2001Node
{
    protected char ch;
    protected Csc2001Node next;

    /*
   * Construct a Csc2001Node with the given character value 
   * @param c - The character 
    */
    public Csc2001Node (char c)
    {
        this.ch = c;
        this.next = null;
    }
}   

我的链表方法class

/*
     * Recursively prints characters in a list
     * @param head The had of current list
     * @return Current list
     */
    private String recursePrintList(Csc2001Node head){

        if(head == null)
            return "List is empty\n";
        else 
            while(head.next!=null)
            {
            return head.ch + "\n" + recursePrintList(head.next); 
            }

        return head.ch + "\n";      
    }    

    /*
     * Wrapper method for printing list
     * @return the list as a string
     */
    public void recursePrintList(){
        System.out.print(recursePrintList(head));   
    }

/*
     * Inserts a character before first occurrence of another specified
     * character in the list.
     * 
     */    
    public Csc2001Node insertBefore(char key, Csc2001Node head, char toInsert)
    {   
        if(head==null){
            return head = new Csc2001Node(toInsert);
        }                       
         else if(head.ch == key)
            return new Csc2001Node(toInsert);
         else
            head.next = insertBefore (key, head.next, toInsert);

         return head;
    }       

    /*
     * Wrapper method for inserting a character before another
     */
    public void insertBefore(char target, char toInsert){
        head = insertBefore(target, head, toInsert);
    }

正在发生的事情的输出

Adding the characters a, s, t, e, r to the list and printing out the list
e
a
s
t
e
r
Testing if the character r is in the list, print out Yes if it is and No otherwise
Yes
Printing out the value of size for this list
6
Trying to insert Y before s in the list and printing out the list
e
a
Y
Printing out the value of size for this list
3
Trying to insert V before e into the front of the list and printing out the list
V
    else if(head.ch == key)
        return new Csc2001Node(toInsert);

正在将新字符作为列表中的最后一个元素,因此您的列表已终止。你想要像

这样的东西
else if (head.next.ch.equals(key)) {
    nextNode = head.next;
    head.next = new Csc2001Node(toInsert);
    head.next.next = nextNode;
}