数组实现栈
import org.apache.poi.ss.formula.functions.T;
public class MyStack {
private int cnt;
private int stackSize;
private T[] arr;
public MyStack(int capacity){
this.cnt = 0;
this.stackSize = capacity;
this.arr = (T[]) new Object[capacity];
}
public boolean isEmpty(){
return this.cnt == 0;
}
public T peak() throws Exception {
if(isEmpty()){
throw new Exception("ERROR");
}
return arr[cnt-1];
}
public T pop() throws Exception {
if(isEmpty()){
throw new Exception("ERROR");
}
T temp = arr[cnt-1];
this.cnt--;
return temp;
}
public void push(T value) throws Exception {
if (stackSize == cnt){
throw new Exception("ERROR");
}
arr[cnt] = value;
this.cnt++;
}
public int getLength(){
return this.cnt;
}
public void clearStack(){
for (int i = 0; i < cnt; i++) {
arr[cnt] = null;
}
this.cnt = 0;
}
}
链表实现栈
链表实现push和pop其实是对表头进行操作,也就是所谓的头插法。
import org.apache.poi.ss.formula.functions.T;
public class MyStack {
private int cnt;
private Node head;
private class Node{
private T value;
private Node next;
public Node(T t, Node next){
this.value = t;
this.next = next;
}
public Node(T t){
this(t,null);
}
}
public MyStack(){
this.cnt = 0;
this.head = null;
}
public boolean isEmpty(){
return this.cnt == 0;
}
public T peak() throws Exception {
if(isEmpty()){
throw new Exception("ERROR");
}
return head.value;
}
public T pop() throws Exception {
if(isEmpty()){
throw new Exception("ERROR");
}
T res = head.value;
head = head.next;
this.cnt--;
return res;
}
public void push(T value) throws Exception {
Node curr = new Node(value);
curr.next = this.head;
this.head = curr;
this.cnt++;
}
public int getLength(){
return this.cnt;
}
public void clearStack(){
this.head = null;
this.cnt = 0;
}
}
|