数据结构之栈知识点
1、静态栈(用数组实现)
代码实现:
public class StackDemo {
private int size;//大小或者容量
private long arr[];//容器
private int top;//栈顶
public StackDemo(int maxsize){
this.size = maxsize;
this.arr = new long[maxsize];
//初始化栈顶,表示为空
this.top = -1;
}
//入栈
public void push(int x){
if (isFull()){
System.out.println("栈已满。");
return;
}
//++top是先+1再运算,所以是从0开始的
//而top++是先运算再加1,所以是从-1开始的
//这里是arr[0]表示第一个元素,后续继续加1
arr[++top] = x;
}
//查看栈顶元素,不删除
public long peek(){
if (isEmpty()){
System.out.println("栈为空。");
return -1;
//throw new RuntimeException("栈是空的");
}
return arr[top];
}
//弹出栈顶元素,删除,并返回栈顶元素
public long pop(){
if (isEmpty()){
System.out.println("栈为空。");
return -1;
}
return arr[top--];
}
//遍历栈,从栈顶开始遍历
public void ergodic(){
for (long i = top;top>-1;top--){
System.out.println(arr[top]);
}
}
//判断栈是否已满
public boolean isFull(){
return size == top - 1;
}
//判断栈是否为空
public boolean isEmpty(){
return top == -1;
}
}
2、动态栈(用链表实现)
代码实现:
public class LinkedStackDemo {
private Node topStack;//栈顶指针
private Node bottomStack;//栈底指针
public int size;
public LinkedStackDemo() {}
public LinkedStackDemo(Node topStack,Node bottomStack){//初始化栈
this.topStack = topStack;
this.bottomStack = bottomStack;
this.size = 0;
}
//入栈
public void push(int data){
Node node = new Node(data);
//引用对象的next指向栈顶节点对象,则栈顶节点对象原先指向的节点,该引用对象新节点的next也同样指向原先指向的节点
node.next = this.topStack;
this.topStack = node;
size++;
}
//弹出栈顶元素,并删除,返回栈顶数值
public int pop(){
if (isEmpty()){
System.out.println("栈为空。");
return -1;
}
int i = this.topStack.data;
this.topStack = this.topStack.next;
size--;
return 1;
}
//查看栈顶数值
public int peek(){
if (isEmpty()){
System.out.println("栈为空。");
return -1;
}
return this.topStack.data;
}
//遍历栈,从栈顶开始
public void ergodic(){
Node currentNode = topStack;
while (currentNode!=null){
System.out.println(currentNode.data);
currentNode = currentNode.next;
}
}
//查看栈中值的数目
public int size(){
return size;
}
//清空栈
public void clear(){
this.topStack = this.bottomStack;//使栈顶元素指向栈底即可清空栈
}
//判断栈是否为空
public boolean isEmpty(){
return size == 0;
}
}
//节点类
class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
}
}
后续如有更优的方法,会继续补充。