标题:
使用Java实现单链表的方法介绍
[打印本页]
作者:
qingqing3721
时间:
2011-8-29 23:32
标题:
使用Java实现单链表的方法介绍
首先构建节点类:
packagecom.fzw.sf; publicclassNode{ privateObjectdata; privateNodenext; Node(Objectdata,Nodenext){ this.data=data; this.next=next; } publicObjectgetData(){ returndata; } publicvoidsetData(Objectdata){ this.data=data; } publicNodegetNext(){ returnnext; } publicvoidsetNext(Nodenext){ this.next=next; } }
其次,构建单链表类:
packagecom.fzw.sf; publicclassList4j{ privateNodehead; privateintlength; publicList4j(){ head=newNode(null,null); length=0; } publicvoidaddhead(Objectitem){ Nodenode=newNode(item,null); node.setNext(head.getNext()); head.setNext(node); length++; } publicvoidaddtail(Objectitem){ Nodenode=newNode(item,null); Nodetemp=head; while(null!=temp.getNext()){ temp=temp.getNext(); } temp.setNext(node); length++; } publicvoidaddindex(Objectitem,intindex){ Nodenode=newNode(item,null); Nodetemp=head; for(inti=0;i temp=temp.getNext(); } node.setNext(temp.getNext()); temp.setNext(node); length++; } publicvoidfind(intindex){ if(index1||indexlength){ System.out.print("此位置空!"); } Nodetemp=head; for(inti=0;i temp=temp.getNext(); } System.out.println("链表中第"+index+"个位置的值为"+temp.getData()); } publicvoiddelindex(intindex){ if(index1||indexlength){ System.out.print("位置不存在!"); } Nodetemp=head; for(inti=0;i temp=temp.getNext(); } temp.setNext(temp.
一生一石珠宝
getNext().getNext()); length--; } publicvoidprint(){ Nodetemp=head; while(null!=temp.getNext()){ System.out.println(temp.getNext().getData()); temp=temp.getNext(); } System.out.println("链表长度为:"+length); } publicstaticvoidmain(String[]args){ List4jlist=newList4j(); list.addhead(2); list.addhead(3); list.addhead(4); list.addtail(5); list.addindex("第二",2); list.print(); list.find(3); } }
欢迎光临 编程开发论坛 (http://bbs.lihuasoft.net/)
Powered by Discuz! 6.0.0