java 中棧的資料結構和佇列的資料結構模型
阿新 • • 發佈:2019-02-13
無意中發現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());
}
}
}