发新话题
打印

使用Java实现单链表的方法介绍

使用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);   }   }
jiyizhen-buy.com颈椎保健枕太空记忆枕 igerl.com歌瑞尔内衣

TOP

发新话题