什么是栈
栈是我们平时用的较多的一个数据结构,它的特点是先进后出,可以做括号匹配,撤销功能等,栈可以用两种最基本的数据结构实现
链式栈
实现代码:
package com.tangbaobao.stack;
import com.tangbaobao.util.Node;
/**
* @author 唐学俊
* @create 2018/03/29
* 链式栈
**/
public class MyStack2 {
int top;
private int bottom;
private Node lastNode = null;
private Node newNode = null;
/**
* 入栈
*
* @param e
*/
public void push(int e) {
newNode = new Node();
newNode.setValue(e);
if (lastNode == null) {
//第一个节点
lastNode = newNode;
} else {
//不是第一个节点
newNode.setNextNode(lastNode);
//记录当前节点,给下次插入使用
lastNode = newNode;
}
top++;
}
/**
* 出栈
*
* @return
*/
public int pop() {
if (top - bottom <= 0) {
try {
throw new Exception("没有啦");
} catch (Exception e) {
e.printStackTrace();
}
} else {
top --;
Node temp = newNode;
newNode = newNode.getNextNode();
return temp.getValue();
}
return -1;
}
}
栈中依赖的链表数据结构
package com.tangbaobao.util;
/**
* 链表的数据结构
*
* @author 唐学俊
* @create 2018/03/29
**/
public class Node {
private Node nextNode;
private int value;
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
顺序栈
用数组作为底层数据结构,入栈按照顺序从0–>n.出栈从n–>1出栈
代码实现
package com.tangbaobao.stack;
/**
* 顺序栈
*
* @author 唐学俊
* @create 2018/03/29
**/
public class MyStack {
private int top;
private int bottom;
private int[] stackData;
/**
* 初始化一个容量为stackzize的栈
*/
public MyStack(int capacity) {
stackData = new int[capacity];
top = 0;
bottom = 0;
}
/**
* 入栈
*
* @param e
*/
public void push(int e) {
//检查栈是否满了
if (top - bottom > stackData.length-1) {
try {
throw new Exception("栈已经满了");
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
//入栈
stackData[top++] = e;
}
}
/**
* 出栈
*
* @return
*/
public int pop() {
//检查栈是否空了
if (top - bottom == 0) {
try {
throw new Exception("栈里面没元素了");
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
return stackData[--top];
}
return -1;
}
}