我更改了LinkedList类,但它仍然不起作用
LinearNode类
public class LinearNode<T>{
private LinearNode<T> next;
private T element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode (T elem)
{
next = null;
element = elem;
}
public LinearNode<T> getNext()
{
return next;
}
public void setNext (LinearNode<T> node)
{
next = node;
}
public T getElement()
{
return element;
}
public void setElement (T elem)
{
element = elem;
}
}
我无法解决java泛型类中delete方法的问题
公共无效删除(T元素){
LinearNode<T> previous = list;
LinearNode<T> current = list;
boolean found = false;
while (!found && current != null)
{
if (current.getElement ().equals (element)) {
found = true;
}
else {
previous = current;
current = current.getNext();
}
}
//found loop
if (found)//we fount the element
{
if(current == this.list){
previous.setNext (null);
this.last = previous;
}
else
if(current == this.last){
this.last.setNext(null);
this.last.equals(previous.getElement());
}
else{
previous.setNext(current.getNext());
current.setNext (null);
}
this.count--;
}
}
我还有我的驱动程序类,它将从链接列表中删除元素
这里也是驾驶员类的一部分
public void delete(){
Teacher aTeacher;
Scanner scan = new Scanner(System.in);
String number;
aTeacher = new Teacher();
System.out.println("Now you can delete teachers from the programme by their number.");
System.out.println("Please input number:");
number = scan.nextLine();
if (aTeacher.getNumber().equals(number)){
teachers.delete(aTeacher);
}
else {
System.out.println("There are no any teacher with this number.");
}
}
我可以在您的代码中看到一些问题。
这个循环有点奇怪
while (current != null && !current.getElement().equals(element))
{
previous = current;
current = current.getNext();
found = true;
}
您不应该在每次迭代中都在循环中设置found = true
,因为这样您就会始终相信您在循环完成后找到了元素。如果您传入您知道列表中存在的值,那么您不会注意到问题。如果传入不在列表中的值,那么稍后在代码中可能会看到current
设置为null
。
我可能会写这个代替
while (! found && current != null)
{
if (current.getElement ().equals (element)) {
found = true;
}
else {
previous = current;
current = current.getNext();
}
}
这个区块也有点奇怪
if(current == this.last){
this.last.setNext(null);
this.last.equals(previous.getElement());
}
这两种说法似乎都不会有任何效果。last.getNext ()
的值应该已经是null
。this.last.equals(previous.getElement())
只是测试最后一个节点是否等于保存在倒数第二个节点中的元素;该评估应该始终是CCD_ 7并且希望没有副作用。
我可能会写这个代替
if(current == this.last){
previous.setNext (null);
this.last = previous;
}
最后,尽管删除本身不是问题,但我仍然会在这里做得很彻底,并确保被删除的节点不会在列表中保留任何引用。
所以这个
previous.setNext(current.getNext());
可能会变成这个
previous.setNext(current.getNext());
current.setNext (null);