0
我想在我的鏈表中更新(替換)方法..我做了添加,搜索和刪除方法,但現在我不知道如何使一個方法,將替換節點中的特定數據例如日期或房間。我希望用戶搜索代碼,然後能夠編輯該特定節點的信息。如何在單鏈表中創建更新方法?
這裏是我的程序:
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;
}
}
}
}
UPDATE:
在這裏,我添加了打印方法的返回類型..它的工作原理,但是當我更新信息沒有關係不打印該節點..任何幫助?
public String printAll()
{
String s = "";
for(myNodes tmp=head;tmp!=null;tmp=tmp.next)
return tmp.toString();
return s;
}
哇老兄你是一個生命的救星!非常感謝!! – Rebecca 2014-11-22 13:34:22
嗯..是否有可能幫助我最後一件事?這是打印方法..我需要把它變成一個返回類型的方法,但是當我這樣做時,它只打印最後一個值。我希望它能打印所有的列表。對不起,如果我聽起來真的很笨,我只是有點新的 – Rebecca 2014-11-22 14:19:58
你想要它返回什麼?一個數組還是隻有一個值?你打算在打印方法之外實現這個功能嗎? – Maor 2014-11-22 14:21:38