我试图在链接列表中创建更新(替换)方法..我已经完成了添加,搜索和删除方法,但现在我不知道如何制作一个方法将替换节点中的特定数据,例如日期或房间。我希望用户搜索代码,然后能够编辑该特定节点的信息。
这是我的计划:
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;
}
}
}
}
更新:
这里我为print方法添加了一个返回类型..它可以工作但是当我更新一个信息时它不会打印那个节点..任何帮助?
public String printAll()
{
String s = "";
for(myNodes tmp=head;tmp!=null;tmp=tmp.next)
return tmp.toString();
return s;
}
答案 0 :(得分:0)
我首先建议按名称搜索是一个不同的功能,删除和更新都使用它,从而使其更易于维护和理解。
其次,如果您正在尝试实施单链表,那么您不应该担心尾巴。
尝试这样的事情:
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是一个带有搜索参数的函数(你可以重载它以获取节点的一个,多个或所有属性)并返回Node本身或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;
}