代码没有对输出进行任何更改,只是重新打印原始链表,我不知道问题出在我的删除方法还是我用于堆栈的访问说明符上。
- 列表项
公共静态类堆栈 {
Node first; *// newest node added*
private int size;
class Node
{
String item;
Node next;
}
public Node delete(int index,Stack list)
{
if (list.first== null) {
return null;
} else if (index == 0)
{
return list.first.next;
}
else
{
Node n = list.first;
for (int i = 0; i < index - 1; i++)
{
n = n.next;
if(i==index)
n.next = n.next.next;//skips over the existing element
}
return list.first;
}
}
}
客户端测试代码
public static void main(String[] args) {
StdOut.print("Type the linked list:");
Stack list = new Stack();
int index;
String in=StdIn.readLine();
for(int i=0;i<=in.length();i++)
{
list.push(in);
}
StdOut.print("Type the index to be deleted:");
index=StdIn.readInt();
StdOut.println("Before deleting element at "+ index);
StdOut.println(in);
StdOut.println("After deleting element at "+ index);
StdOut.print(list.delete(index,list).item);
}
}
在你的 delete(( 函数中,你返回的是list.first
- 它指向列表的头节点,而不是Node first* //newest node added*
,对吗?我认为您应该在删除任务完成时从函数返回,而不是返回null
或node
。
此外,当您循环访问 final else 语句中的列表时,应将n = n.next;
行移动到索引检查下方。
你的 delete(( 函数看起来像这样:
public Node delete(int index,Stack list)
{
if (list.first== null)
{
return;
} else if (index == 0)
{
return;
}
else
{
Node n = list.first;
for (int i = 0; i < index; i++)
{
//If the next Node of the current node is +1 the current index
if(i+1==index)
{
n.next = n.next.next;//skips over the existing element
return;
}
n = n.next;
}
return;
}
}
和:
list.delete(index,list).item; //call the delete function
StdOut.println("After deleting element at "+ index);
list.print(); //Print the list using its print function (assuming you have one)
我希望这有帮助!