我正在尝试在我的链表中更新(替换)方法。我已经完成了添加,搜索和删除方法,但现在我不知道如何制作一种方法来替换节点中的特定数据,例如日期或房间。我希望用户搜索代码,然后能够编辑该特定节点的信息。
这是我的程序:
public class myNodes {
public String name,department,code;
public Object date,time;
public myNodes next;
public int room;
public myNodes(String name,String department,String code,Object date,Object time,int room)
{
this(name,department,code,date,time,room,null);
}
public myNodes (String name,String department,String code,Object date,Object time,int room,myNodes n)
{
this.name=name;
this.department=department;
this.code=code;
this.date=date;
this.time=time;
this.room=room;
next=n;
}
class MyList1 {
protected myNodes head,tail;
public MyList1()
{
head=tail=null;
}
public void addToHead(String name,String department,String code,Object date,Object time,int room)
{
head=new myNodes (name,department,code,date,time,room,head);
if(tail == null)
tail=head;
}
public String deleteFromHead()
{
String e1=head.name+head.department+head.code+head.date+head.time+head.room;
if(head==tail)
head=tail=null;
else
head=head.next;
return e1;
}
public void printAll()
{
if(head!=null)
{
for(myNodes tmp=head;tmp!=null;tmp=tmp.next)
System.out.println (tmp.name+"t"+tmp.department+"t"+tmp.code+"t"+tmp.date+"t"+tmp.time+"t"+tmp.room+"n");
}
else
System.out.println("The list is empty");
}
//Search by code
public boolean Search(String e1)
{
myNodes tmp;
for(tmp=head;tmp!=null && !tmp.code.equals(e1); tmp=tmp.next);
return tmp!=null;
}
//delete by code
public void delete(String e1)
{
if(head != null)
{
if(head == tail && e1.equalsIgnoreCase(head.code))
head=tail=null;
else if (e1 == head.code)
head=head.next;
else
{
myNodes pred,tmp;
for(pred=head,tmp=head.next; tmp!=null && tmp.code.equalsIgnoreCase(e1);
pred=pred.next,tmp=tmp.next);
if (tmp!=null)
pred.next=tmp.next;
if(tmp==tail)
tail=pred;
}
}
}
}
更新:
在这里,我为打印方法添加了返回类型..它有效,但是当我更新信息时,它不会打印该节点..有什么帮助吗?
public String printAll()
{
String s = "";
for(myNodes tmp=head;tmp!=null;tmp=tmp.next)
return tmp.toString();
return s;
}
我首先建议按名称搜索将是一个不同的功能,删除和更新都使用它,从而使它更易于维护且更易于理解。
其次,如果你试图实现一个单向链表,你不应该担心尾巴。
尝试这样的事情:
public boolean editNode(String searchValue, String newValue)
{
boolean success = False;
myNodes tmp = searchByCode(searchValue);
if (tmp != Null) //It would be better to use exceptions
{
tmp.setName(newValue); //I'm assuming you have getters and setters. and of course you could do anything else in here
success = True;
}
return success;
}
其中 searchByName 是一个函数,它接受一个搜索参数(你可以重载它来获取节点的一个、多个或所有属性)并返回节点本身或 null(null 部分不是必需的,只是为了让它与上面的特定函数一起工作。同样如上所述,最好使用例外,但以防万一我假设您还没有使用这些例外。
searchByCode 函数可以执行以下操作:
public myNodes searchByCode(String e1) //Assuming you have a single occurrence of code in your list, otherwise, it returns the last occurrence
{
myNodes tmp, retVal = null;
for(tmp=head; tmp!=null; tmp=tmp.next)
{
if (e1.equalsIgnoreCase(tmp.getCode()))
{
retVal = tmp;
}
}
return retVal
}
对于您的更新,请对此进行更改:
public String printAll()
{
String s = "";
for(myNodes tmp=head;tmp!=null;tmp=tmp.next)
s += tmp.toString();
return s;
}