栈
一种特殊的线性表,只允许在固定的一端进行插入和删除元素操作。栈中的数据元素遵循先进后出的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据在栈顶。
栈的实现:
public class MyStack<T> {
private T[] elem;
private int size;
public MyStack() {
this.elem = (T[])new Object[10];
this.size = 0;
}
/**
* 入栈
* @param val
*/
public void push(T val){
if(full()){
return;
}
this.elem[this.size]=val;
size++;
}
/**
* 出栈
*/
public T pop(){
if(empty()){
throw new RuntimeException("栈为空!");
}
T data = this.elem[this.size-1];
this.size--;
return data;
}
/**
* 查看栈顶元素
*/
public T peek(){
if(empty()){
throw new RuntimeException("栈为空!");
}
T data = this.elem[this.size-1];
return data;
}
/**
* 判断是否为空
* @return
*/
public boolean empty(){
if(size==0){
return true;
}
return false;
}
/**
* 判断是否为满
* @return
*/
public boolean full(){
if(size==elem.length){
return true;
}
return false;
}
public static void main(String[] args) {
MyStack<Integer> myStack = new MyStack<Integer>();
myStack.push(10);
myStack.push(20);
myStack.push(30);
myStack.push(40);
myStack.push(50);
System.out.println(myStack.pop());
System.out.println(myStack.peek());
}
}
队列
一种特殊的线性表,只允许在一端进行插入数据操作,在另一端进行删除数据操作。队列具有先进先出的特点。
入队列:进行插入操作的一端称为队尾。
出队列:进行删除操作的一端称为队头。
- 循环队列:循环队列是一种线性数据结构,基于先进先出的原则并且队尾被连接在队首之后以形成一个循环。循环队列通常用数组实现。
- 双端队列:指允许两端都可以进行入队和出队操作的队列。
队列的实现:
class Node{
public int data;
public Node next;
public Node(){}
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class MyQueue<T> {
public Node front;
public Node rear;
public int size;
/**
* 入队
* @param data
*/
public void offer(int data){
Node node = new Node(data);
if(this.size==0){
this.front = node;
this.rear = node;
this.size++;
return;
}
this.rear.next = node;
this.rear = node;
this.size++;
}
/**
* 出队
* @return
*/
public int poll(){
if(empty()){
throw new RuntimeException("队列为空!");
}
int data = this.front.data;
this.front = this.front.next;
this.size--;
return data;
}
/**
* 队首元素
* @return
*/
public int peek() {
if (empty()) {
throw new RuntimeException("队列为空!");
}
return this.front.data;
}
public boolean empty(){
return this.size==0;
}
public static void main(String[] args) {
MyQueue<Integer> myQueue = new MyQueue<>();
myQueue.offer(1);
myQueue.offer(3);
myQueue.offer(4);
myQueue.offer(10);
System.out.println(myQueue.poll());
System.out.println(myQueue.peek());
}
}
队列中 add() 和 offer() 都是用来向队列添加一个元素。在队列已满的情况下,add() 方法会抛出异常让你处理,offer() 方法只会返回 false 。在队列中,最好使用offer()方法。