栈
先进后出FILO,在表的一端进行操作
1.顺序存储
2.链式存储
class Stack{
//顺序栈
private int top = -1; //栈顶 ,-1表示栈为空
private int size; // 栈内的元素个数
private int capacity = 10; //栈的容量
private int[] array; //存放栈元素
public Stack(int capacity) {
super();
this.capacity = capacity;
array = new int[capacity];
}
public Stack() {
super();
array = new int[this.capacity];
}
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty() {
return this.top == -1;
}
/**
* 入栈 push
* @return
*/
public void push(int data) {
//判断栈是否满了
if(array.length == size) {
//扩容
increCapacity();
}
array[++top] = data;
size++;
}
/**
* 出栈
* 1.栈空,抛异常
* 2.栈不为空:size减一,移动栈顶指针
* @return
* @throws Exception
*/
public int pop() throws Exception {
if (this.isEmpty()) {
throw new Exception("stack is empty !");
}
this.size--;
return array[this.top--];//返回栈顶元素,移动栈顶指针
}
//获取栈顶元素
public int getTopData() {
if (isEmpty()) {
return -1;
}
return array[this.top];
}
/**
* 扩容
*/
public void increCapacity() {
this.capacity = this.size * 2 + 1; //默认
int[] old_array = this.array;
array = new int[this.capacity];
System.arraycopy(old_array, 0, array, 0, size);
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
class Node{
Integer data;
Node last;
public Node(int data,Node last) {
super();
this.data = data;
this.last = last;
}
public Node(int data) {
super();
this.data = data;
}
public Node() {
super();
}
}
class LinkStack{
//链式栈
private Node top;
private int size;
public LinkStack() {
this.top = new Node();
}
/**
* 入栈
* 1. null 不允许入站
* 2. 判断是否为空栈
* @throws Exception
*/
public void push(Integer data) throws Exception {
if (data == null) {
throw new Exception(" data can't be null");
}else if (isEmpty() ) {
Node node = new Node(data,null);
this.top = node;
}else {
Node node = new Node(data,this.top);
this.top = node;
}
size++;
}
/**
* 出zhan
* @throws Exception
*/
public int pop() throws Exception {
if (isEmpty()) {
throw new Exception("stack is empty !");
}
int data = this.top.data;
this.top = this.top.last;
size--;
return data;
}
public Integer getTopData() {
if (isEmpty()) {
return null;
}
return this.top.data;
}
/**
* 判断是否为空
* @return
*/
public boolean isEmpty() {
return (this.top == null || this.top.data == null);
}
public Node getTop() {
return top;
}
public void setTop(Node top) {
this.top = top;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}