gpt4 book ai didi

java - 递归单链表插入Before方法切断列表的其余部分

转载 作者:行者123 更新时间:2023-12-02 04:52:21 25 4
gpt4 key购买 nike

在使用递归方法创建手动链表时,我无法弄清楚为什么我的 Insert Before 方法在插入新节点后会切断列表。该列表未排序。我对此很陌生,任何关于为什么会发生这种情况的帮助将不胜感激。

我的节点类

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;
}
}

链接列表类中的我的方法

/*
* 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;
}

关于java - 递归单链表插入Before方法切断列表的其余部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com