栈介绍
栈这个东西,也没啥,说白了就是先进后出(LIFO, Last In First Out)的一种数据结构,主要分为静态栈和动态栈,静态栈一般由数组实现,而动态栈则通过链表实现,本文将演示两种栈的创建及其相关操作。本文仅为个人学习的记录,仅供参考。
相关操作介绍
- 元素的入栈
- 元素的出栈
- 返回栈的长度
- 判断是否为空栈
- 栈的生成
- 栈的清空
Java实现
静态栈
package stack;
public class MyStaticStack {
private Integer[] stack;
private int size = 0;
public MyStaticStack() {
stack = new Integer[10];
}
/**
* 构造方法
*
* @param size 栈大小
*/
public MyStaticStack(int size) {
stack = new Integer[size];
}
/**
* 入栈
*
* @param value 值
*/
public void push(int value) {
if (size >= stack.length) {
//栈满抛出异常
throw new RuntimeException("Stack Overflow");
}
stack[size] = value;
size++;
}
/**
* 获取栈顶元素
*
* @return 栈顶元素
*/
public Integer peek() {
if (size < 1) {
return null;
}
return stack[size - 1];
}
/**
* 出栈
*
* @return 栈顶元素
*/
public Integer pop() {
if (size > 0) {
size--;
return stack[size];
}
return null;
}
/**
* 返回栈的长度
*
* @return 栈的长度
*/
public int getSize() {
return size;
}
/**
* 判断是否为空
*
* @return 是否为空
*/
public boolean isNull() {
return size == 0;
}
/**
* 清空栈
*/
public void clear() {
size = 0;
}
}
动态栈
package stack;
public class MyDynamicStack {
/**
* 链表节点内部类
*/
class Node {
public Integer data;
public Node next;
public Node() {
}
public Node(int data) {
this.data = data;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
private Node top;
private int size = 0;
public MyDynamicStack() {
top = new Node();
}
/**
* 入栈
*
* @param value 值
*/
public void push(int value) {
top = new Node(value, top);
size++;
}
/**
* 获取栈顶元素
*
* @return 栈顶元素
*/
public Integer peek() {
return top.data;
}
/**
* 出栈
*
* @return 栈顶元素
*/
public Integer pop() {
if (size < 1) {
return null;
}
size--;
int res = top.data;
top = top.next;
return res;
}
/**
* 返回栈的长度
*
* @return 栈的长度
*/
public int getSize() {
return size;
}
/**
* 判断是否为空
*
* @return 是否为空
*/
public boolean isNull() {
return size == 0;
}
/**
* 清空栈
*/
public void clear() {
size = 0;
top = null;
}
}
测试类
package stack;
public class Test {
public static void main(String[] args) {
MyStaticStack myStaticStack = new MyStaticStack();
myStaticStack.push(1);
myStaticStack.push(2);
myStaticStack.push(3);
System.out.println(myStaticStack.peek());
System.out.println(myStaticStack.pop());
System.out.println(myStaticStack.peek());
System.out.println(myStaticStack.getSize());
System.out.println(myStaticStack.isNull());
myStaticStack.clear();
System.out.println(myStaticStack.isNull());
MyDynamicStack myDynamicStack = new MyDynamicStack();
myDynamicStack.push(4);
myDynamicStack.push(5);
myDynamicStack.push(6);
System.out.println(myDynamicStack.peek());
System.out.println(myDynamicStack.pop());
System.out.println(myDynamicStack.peek());
System.out.println(myDynamicStack.getSize());
System.out.println(myDynamicStack.isNull());
myDynamicStack.clear();
System.out.println(myDynamicStack.isNull());
}
}