无意中发现LinkedList 不仅仅实现了List接口,同时也实现了Queue接口,因此在这里就模拟一下栈的数据结构和队列的数据结构。为以后的面试做准备。
/**
* @author yikai
* 栈类型的数据结构的特点就是先进后出,那么这就简单了,就是在取值的时候,取出容器中
* 最后的值
*/
public class StackDemo<E> {
private LinkedList<E> linkedList = new LinkedList();
//压栈操作,就是往容器中添加数据
public void push(E e) {
linkedList.offer(e);
}
//出栈操作,就是先取出容器中后放入的数据
public E pop() {
if (linkedList.size() > 0) {
return linkedList.removeLast();
} else {
throw new IllegalStateException();
}
}
}
/**
* @author yikai
* 队列数据结构的特点就是先进先出,那么取值的时候就取最先放入的值
*/
public class QueueDemo<E> {
private LinkedList<E> linkedList = new LinkedList<>();
//入队操作,往队列中添加数据
public void enqueue(E e) {
linkedList.offer(e);
}
//出队操作,取出队列中的对首元素
public E dequeue() {
if (linkedList.size() > 0) {
return linkedList.removeFirst();
} else {
throw new IllegalStateException();
}
}
}
/**
* @author yikai
* 测试类
*/
public class TestDemo {
public static void main(String[] arg0){
System.out.println("------------栈模型-----------------");
StackDemo<String> stackDemo = new StackDemo();
stackDemo.push("a");
stackDemo.push("b");
stackDemo.push("c");
stackDemo.push("d");
for (int i = 0; i < 4; i++) {
System.out.println(stackDemo.pop());
}
System.out.println("------------队列模型---------------");
QueueDemo<String> queueDemo = new QueueDemo<>();
queueDemo.enqueue("a");
queueDemo.enqueue("b");
queueDemo.enqueue("c");
queueDemo.enqueue("d");
for (int i = 0; i < 4; i++) {
System.out.println(queueDemo.dequeue());
}
}
}