1、栈的实现
栈的功能:进栈、出栈、返回栈口元素……
package com.example.designpatterns.controller;
import org.springframework.util.CollectionUtils;
import java.util.EmptyStackException;
import java.util.LinkedList;
/**
* 用list 实现栈
* 栈的功能:进栈、出栈、返回栈口元素…… 先进后出
*/
public class MyStack {
private LinkedList li = null;
public MyStack() {
li = new LinkedList();
}
//出栈
public Object pop(){
if(isEmpty())
throw new EmptyStackException();
return li.removeFirst();
}
private boolean isEmpty(){
if (CollectionUtils.isEmpty(li)) return true;
return false;
}
//入栈
public void push(Object obj){
li.addFirst(obj);
}
//清空
public void clear(){
li.clear();
}
//返回栈口元素(不删除)
public Object peek(){
if (isEmpty()) throw new EmptyStackException();
return li.getFirst();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
//入栈
stack.push("a");
stack.push("b");
stack.push("c");
//出栈
System.out.println(stack.pop());
//返回栈口元素
System.out.println(stack.peek());
}
}
2. 队列的实现:
队列的功能:队尾进,队首出、....
package com.example.designpatterns.controller;
import org.springframework.util.CollectionUtils;
import java.util.EmptyStackException;
import java.util.LinkedList;
/**
* 借助Linklist 实现队列
* 队列的功能:队尾进,队首出
*/
public class MyQueue {
private LinkedList li = null;
public MyQueue() {
li = new LinkedList();
}
private boolean isEmpty(){
if (CollectionUtils.isEmpty(li)) return true;
return false;
}
//出列
public Object get(){
if(isEmpty()) throw new EmptyStackException();
return li.removeFirst();
}
//进列
public void put(Object obj){
li.addLast(obj);
}
public void clear(){
li.clear();
}
//返回队首元素(不删除)
public Object getTop(){
if(isEmpty()) throw new EmptyStackException();
return li.getFirst();
}
public static void main(String[] args) {
MyQueue mq = new MyQueue();
//进列
mq.put("a");
mq.put("b");
mq.put("c");
//出列
System.out.println(mq.get());
//返回对首元素
System.out.println(mq.getTop());
}
}