疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

用java实现单链表


 

publicclassNode {
 
privateObject data;
 
privateNode next;
 
Node(Object data,Node next){
this.data = data;
this.next = next;
}
 
publicObject getData() {
returndata;
}
 
publicvoidsetData(Object data) {
this.data = data;
}
 
publicNode getNext() {
returnnext;
}
 
publicvoidsetNext(Node next) {
this.next = next;
}
 
}
其次,构建单链表类:
 
publicclassList {
privateNode head ;
privateintlength;
 
publicList(){
head =newNode(null,null);
length = 0;
}
 
publicvoidaddhead(Object item){
Node node =newNode(item,null);
node.setNext(head.getNext());
head.setNext(node);
length++;
}
 
publicvoidaddtail(Object item){
Node node =newNode(item,null);
Node temp = head;
while(null!= temp.getNext()){
temp = temp.getNext();
}
temp.setNext(node);
length++;
}
 
publicvoidaddindex(Object item,intindex){
Node node =newNode(item,null);
Node temp = head;
for(inti=0; i<index-1;i++){
temp = temp.getNext();
}
node.setNext(temp.getNext());
temp.setNext(node);
length++;
 
}
 
publicvoidfind(intindex){
if(index<1 || index >length){
System.out.print("此位置空!");
}
Node temp = head;
for(inti=0; i<index;i++){
temp = temp.getNext();
}
System.out.println("链表中第"+index+"个位置的值为"+temp.getData());
}
 
publicvoiddelindex(intindex){
if(index<1 || index >length){
System.out.print("位置不存在!");
}
Node temp = head;
for(inti=0; i<index-1;i++){
temp = temp.getNext();
}
temp.setNext(temp.getNext().getNext());
length--;
 
}
 
 
publicvoidprint(){
Node temp = head;
while(null!= temp.getNext()){
System.out.println(temp.getNext().getData());
temp = temp.getNext();
}
System.out.println("链表长度为:"+length);
}
 
publicstaticvoidmain(String[] args){
List list =newList();
list.addhead(2);
list.addhead(3);
list.addhead(4);
list.addtail(5);
list.addindex("第二", 2);
 
list.print();
list.find(3);
 
}
}