我写的是size,lastElement,reverse,append函数,不知道对不对?再者,我想把该模板实例化成结点数据为int类型的这么一个链表,但是我不知道该怎么实例化成int类型,我只知道byte类型的...
我写的是size,lastElement,reverse,append函数,不知道对不对?再者,我想把该模板实例化成结点数据为int类型的这么一个链表,但是我不知道该怎么实例化成int类型,我只知道byte类型的实例化,求指教!(链表的main函数是不正确的,只是借其表达实例化的意思,想实例化成int的,然后操作链表、打印等)
class llist{
private T datum=null;
llist rest=null;
llist(){}
private llist(T datum,llist l){
this.datum=datum;
this.rest=l;
}
public llist prepend(T datum){ return new llist(datum,this); }
public T first(){
if(this.rest!=null){
return this.datum;
}else{
throw new NullPointerException();
}
}
public llist rest(){
if(this.rest!=null){
return this.rest;
}else{
throw new NullPointerException();
}
}
public boolean empty(){ return (this.rest==null); }
public void setFirst(T datum){
if(!this.empty())this.datum=datum; }
public llist setRest(llist l){
if(this.rest!=null){
this.rest=l;
return this;
}else{
throw new NullPointerException();
}
}
/
//
//COMPLETE SIZE (PROBLEM 1)
public int size(){
if(this.datum==null)return 0;
else{
int size=1;
for(;this.rest!=null;this.rest=this.rest.rest){
size++;
}
return size;
}
}
/
//
//COMPLETE LASTELEMENT (PROBLEM 1)
public llist lastElement(){
if(this.datum==null) return null;
llist l=this;
for(int i=0;i<=this.size();i++){
if(!l.empty()){
l=l.rest;
}
}
return l; }
/
//
//COMPLETE REVERSE (PROBLEM 1)
public llist reverse(){ //雷同数据结构链表快速转置的做法
if(this.datum==null||this.rest==null)
return this;
llist l1,l2,l3;//node *temp1,*temp2,*temp3;
l1=this;//temp1=head;
l2=this.rest;//temp2=temp1->next;
l3=l2.rest;//temp3=temp2->next;
l1.setRest(null);//head->next=NULL;
while(l3!=null)//while(temp3!=NULL)
{
l2.setRest(null);
l2.setRest(l1); // temp2->next=temp1;
l1=l2;// temp1=temp2;
l2=l3;//temp2=temp3;
l3=l3.rest; // temp3=temp3->next;
}
l2.setRest(null);
l2.setRest(l1); //temp2->next=temp1;
//return temp2
return l2;
}
/
//
//COMPLETE APPEND (PROBLEM 1)
public llist append(llist l){
if(this.lastElement()!=null){
this.lastElement().setRest(l);}
return this; }
public static void main(String[] args )
{
llist l=new llist();
l.prepend((byte)1);
l.prepend((byte)2);
l.prepend((byte)3);
l.prepend((byte)4);
System.out.println(l);
System.out.println(l.size());
llist l2=new llist();
l.prepend((byte)5);
System.out.println(l.append(l2));
System.out.println(l.reverse());
System.out.println(l.lastElement());
}
}
展开