队列先进先出,因此此处采用尾插法进行链表创建,同时需要标记head ,tail
public class List {
int content;
List next;
public List(int content,List next){
this.content=content;
this.next=next;
}
public static List insert(List list,int context){
return new List(context,list);
}
}
上面的代码是创建链表的过程
package base;
import java.util.Scanner;
public class Queue {
List head;
List tail;
public Queue(){
this.head=null;
this.tail=head;
}
public void pop(int context){
if(this.head==null){
this.head=List.insert(this.head, context);
this.tail=this.head;
}
else{
List temp=List.insert(null, context);
this.tail.next=temp;
this.tail=this.tail.next;
}
}
public int pull(){
if(this.head==null){
System.out.println("队列已经为空");
return -1;
}
else{
int context=this.head.content;
this.head=this.head.next;
return context;
}
}
public static void main(String[] args) {//基于链表的队列实现;
// TODO Auto-generated method stub
Queue qu=new Queue();
Scanner input =new Scanner(System.in);
String number=input.nextLine();
while(!number.equals("end")){
qu.pop(Integer.parseInt(number));
number=input.nextLine();
}
System.out.println("队列进入完毕");
while(qu.head!=null){
System.out.println(qu.pull());
}
}
}