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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java集合框架:浅谈如何使用LInkedList实现队列(Queue)和堆栈(Stack)相关的知识,希望对你有一定的参考价值。

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)的主要内容,如果未能解决你的问题,请参考以下文章

浅谈java集合

浅谈java类集框架和数据结构

浅谈Java集合框架

浅谈Java集合(底层源码解析)

Java集合框架----LinkedList源码

Java集合框架----LinkedList源码