1.栈及其Java实现
栈(Stack)又名堆栈,是允许在同一端进行插入和删除操作的特殊线性表。其中,允许进行插入和删除操作的一端叫作栈顶(Top),另一端叫作栈底(Bottom),栈底固定,栈顶浮动。栈中的元素个数为零时,该栈叫作空栈。插入一般叫作进栈(Push),删除叫作退栈(Pop)。栈也叫作后进先出(FILO-First In Last Out)的线性表
public class Stack<E> {
private Object[] data = null;
private int maxSize = 0; //栈的容量
private int top = -1; //栈顶的指针
Stack() {
this(10);
}
Stack(int initialSize) {
if (initialSize >= 0) {
this.maxSize = initialSize;
data = new Object[initialSize];
top = -1;
} else {
throw new RuntimeException("初始化大小不能小于0");
}
}
//进栈
//栈顶元素的指针是从 0开始计算的
//Stack<E>
public boolean push(E e) {
if (top == maxSize - 1) {
throw new RuntimeException("栈已经满了,元素将无法入栈");
} else {
data[++top] = e;
return true;
}
}
//出栈
public E pop(){
if(top ==-1){
throw new RuntimeException("栈为空");
}else{
//data[top--]先取data[top]再top-1
//data[--top]先result=top-1再data[先result]
return (E)data[top--];
}
}
public E peek(){
if(top==-1){
throw new RuntimeException("栈为空");
}else{
return (E)data[top];
}
}
public static void main(String[] args) {
Stack stack=new Stack();
stack.push("测试1");
stack.push("测试2");
String str= (String)stack.peek();
System.out.println(str);
String str1=(String) stack.pop();
System.out.println(str1);
String str2= (String)stack.peek();
System.out.println(str2);
}
结果:
2.队列及其Java实现
队列的基本特性就是先进先出(FIFO)
package datasStructure;
/**
* @program: practise-model
* @description:
* @author: lbw
* @create: 2022-04-06 11:06
**/
//队列及java实现
public class Queue<T> {
private T[] data = null;
//队列中的个数
private int size;
//列队头,允许删除
private int front;
//列队尾,允许插入
private int rear;
public Queue() {
this(10);
}
public Queue(int initialSize) {
if (initialSize >= 0) {
//this.size = initialSize;
data = (T[]) new Object[10];
front = rear = 0;
} else {
throw new RuntimeException("初始化大小不能小于0" + initialSize);
}
}
//在队列的尾部添加数据
public void add(T t) {
if (isFull()) {
resize();
front = 0;
}
rear = (front + size) % data.length;
System.out.println(t + "插入得位置是" + rear);
data[rear] = t;
size++;
}
//删除队列的头部元素
public T remove() {
if (isEmpty()) {
throw new RuntimeException("空队列异常");
} else {
//临时保存队列front端的元素的值
T value = (T) data[front];
data[front++] = null;
front = (front + 1) % (data.length);
size--;
System.out.println("删除队列头部的元素" + value);
return value;
}
}
//取出队列头部的元素,但不删除
public T peek() {
if (data == null) {
throw new RuntimeException("空队列异常");
} else {
//
System.out.println("取出队列头部的元素" + data[front]);
return (T) data[front];
}
}
public boolean isFull() {
return size == data.length;
}
public boolean isEmpty() {
return size == 0;
}
//扩容
public void resize() {
T[] tmp = (T[]) new Object[data.length * 2];
System.arraycopy(data, 0, tmp, 0, data.length);
data = tmp;
tmp = null;
}
public static void main(String[] args) {
Queue queue = new Queue();
queue.add("1");
queue.add("2");
queue.add("3");
queue.peek();
queue.remove();
}
}
结果是: