Topic: 我要如何创建单向链表?

  Print this page

1.我要如何创建单向链表? Copy to clipboard
Posted by: cyy
Posted on: 2006-01-11 22:04

原代码如下,为书上的例子:

class Entry{
Object element;
Entry next;
Entry(Object element) {
this.element=element;
this.next=null;
}
Object getElement(){
return element;
}
}
public class SinglyList1{
Entry header=new Entry(null);

Entry add(Object o){
Entry newEntry=new Entry(o);
Entry e=header;
while(e.next!=null)
e=e.next;
e.next=newEntry;
return newEntry;
}
Entry remove(){
Entry e=header;
if (e.next.next==null) return null;
while (e.next.next!=null)
e=e.next;
Entry temp=e.next;
e.next=null;
return temp;
}
public static void main(String[] args){
Object ob1=new Object();
Object ob2=new Object();
Object ob3=new Object();
SinglyList1 list=new SinglyList1();
list.add("苹果");
list.add("香蕉");
list.add("柑橘");
System.out.println(list.remove().getElement());
System.out.println(list.remove().getElement());
System.out.println(list.remove().getElement());
}
}

但是在编译时出现错误,错误如下:
--------------------Configuration: <Default>--------------------
C:\thinkinjava\SinglyList1.java:37: add(Object) in SinglyList1 cannot be applied to (java.lang.String)
list.add("苹果");
^
C:\thinkinjava\SinglyList1.java:38: add(Object) in SinglyList1 cannot be applied to (java.lang.String)
list.add("香蕉");
^
C:\thinkinjava\SinglyList1.java:39: add(Object) in SinglyList1 cannot be applied to (java.lang.String)
list.add("柑橘");
^
3 errors
说是ADD这个方法不能应用到字符串中,为什么呢?难道是书上有错还是我的代码那里出现问题,对照书上的例子几遍都没有查出来,请各位大哥大姐帮小弟看一看,谢谢了!!

2.Re:我要如何创建单向链表? [Re: cyy] Copy to clipboard
Posted by: cyy
Posted on: 2006-01-13 11:40

怎么这么久还没有人帮忙啊?看来这个网站的人气不怎么样!!

3.Re:我要如何创建单向链表? [Re: cyy] Copy to clipboard
Posted by: why
Posted on: 2006-01-13 12:42

照呀,人氣不怎麼樣
愛熱鬧就不要來吧Smile

代碼應該沒問題--雖然執行時會有Null Exception
試試把SinglyList1.java抄到別的folder再compile看看
不妨把Command Prompt上執行的都貼上來,即
>type SinglyList1.java

>javac -cp . SinglyList1.java

4.Re:我要如何创建单向链表? [Re: cyy] Copy to clipboard
Posted by: athlon
Posted on: 2006-01-17 11:07

个人认为程序的这里有点问题:

if (e.next.next==null)
return null;

可以修改成

if (e.next==null)
return null;

5.Re:我要如何创建单向链表? [Re: cyy] Copy to clipboard
Posted by: npwinterboy
Posted on: 2006-01-18 13:20

我全部考下来,然后在JCreator里面编译,没有出任何问题啊,哪里有什么编译的问题?

6.Re:我要如何创建单向链表? [Re: cyy] Copy to clipboard
Posted by: esidemayi
Posted on: 2006-01-19 16:11

System.out.println(list.remove().getElement());
System.out.println(list.remove().getElement());
System.out.println(list.remove().getElement());

第三个remove()后就这个连表就是一个NULL怎么可能取到值呢

7.Re:我要如何创建单向链表? [Re: cyy] Copy to clipboard
Posted by: sam_wangyl
Posted on: 2006-02-07 14:50

请问各位:Object 究竟该怎么理解它?
一直很糊涂。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923