码迷,mamicode.com
首页 > 编程语言 > 详细

java集合框架:浅谈如何使用LInkedList实现队列(Queue)和堆栈(Stack)

时间:2018-10-08 20:33:14      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:return   void   get   实现   last   堆栈   浅谈   oid   sys   

Java中的LinkedList?是采用双向循环列表实现的。
利用LinkedList?可以实现栈(stack)、队列(queue)

下面写两个例子
学生类:
int stuId;

public int getStuId() {
    return stuId;
}
public void setStuId(int stuId) {
    this.stuId = stuId;
}
public String getStuName() {
    return stuName;
}
public void setStuName(String stuName) {
    this.stuName = stuName;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
String stuName;

int age;

public Student(){

}
public Student(int stuId,String stuName,int age){
    this.age = age;
    this.stuId = stuId;
    this.stuName = stuName;
}
public String toString() {

return ("学生姓名:"+this.stuName+"学生年龄"+this.age+"学生编号"+this.stuId);

}

队列
自定义方法实现LInkedList
LinkedList lists =new LinkedList();

public  void push(Object object){
    lists.addLast(object);
}
public Object pop(){
    return lists.removeFirst();
}

实现方法
System.out.println("在队列中添加对象");
MyQuene quene = new MyQuene();
quene.push(new Student(1,"学生1",20));
quene.push(new Student(2,"学生2",21));
quene.push(new Student(3,"学生3",23));
for (Object object : quene.lists) {
Student student = (Student)object;
System.out.println(student.toString());
}
System.out.println("在队列中删除对象");
quene.pop();
for (Object object : quene.lists) {
Student student = (Student)object;
System.out.println(student.toString());
}

堆栈:

自定义方法,并实现

LinkedList lists =new LinkedList();

public void push(Object object){
    lists.addFirst(object);
}

public Object pop(){
    return lists.removeLast();
}

System.out.println("在队列中添加对象");
MyStack Stack = new MyStack();
Stack.push(new Student(1,"学生1",20));
Stack.push(new Student(2,"学生2",21));
Stack.push(new Student(3,"学生3",23));
for (Object object : Stack.lists) {
Student student = (Student)object;
System.out.println(student.toString());
}
System.out.println("在队列中删除对象");
Stack.pop();
for (Object object : Stack.lists) {
Student student = (Student)object;
System.out.println(student.toString());
}

java集合框架:浅谈如何使用LInkedList实现队列(Queue)和堆栈(Stack)

标签:return   void   get   实现   last   堆栈   浅谈   oid   sys   

原文地址:http://blog.51cto.com/13758648/2296002

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!