/**
*数组实现栈,需要"数组,末端索引,初始容量"
*/
public class ArrayStack {
//数组初始容量,由于是数组实现,需要考虑扩容问题
private int DEFAULT_CAPCITY = 10;
private int[] array;
private int topOfStack = -1;
// 使用默认初始容量
public ArrayStack(){
array = new int[DEFAULT_CAPCITY];
}
// 使用指定初始容量
public ArrayStack(int capacity){
array = new int[capacity];
}
public void makeEmpty(){
topOfStack = -1;
}
public boolean isEmpty(){
return topOfStack == -1;
}
public void push(int x){
// 此时需要扩容
if(topOfStack + 1 == array.length){
array = Arrays.copyOf(array,DEFAULT_CAPCITY*2);
}
array[++topOfStack] = x;
}
public void pop(){
if(isEmpty()){
return;
}
topOfStack--;
}
}
链表实现栈
/**
* 链表实现栈,链表的第一项表示栈顶元素
*/
public class ListNodeStack {
class ListNode{
public int element;
public ListNode next;
public ListNode(int theElement, ListNode theNext){
this.element = theElement;
this.next = theNext;
}
}
private ListNode topOfStack = null;
public void makeEmpty(){
topOfStack = null;
}
public boolean isEmpty(){
return topOfStack == null;
}
public void push(int x){
topOfStack = new ListNode(x,topOfStack);
}
public void pop(){
if(isEmpty()){
return;
}
topOfStack = topOfStack.next;
}
}
链表实现队列
/**
* 链表实现队列,需要"队首元素和队尾元素的引用"
*/
public class ListNodeQueue {
class ListNode{
private ListNode next;
private int element;
public ListNode(int theElement, ListNode theNext){
this.element = theElement;
this.next = theNext;
}
}
private ListNode front = null;
private ListNode back = null;
public void makeEmpty(){
front = null;
back = null;
}
public boolean isEmpty(){
return front == null;
}
public void enqueue(int x){
if(isEmpty()){
front = new ListNode(x,null);
back = front;
} else {
back.next = new ListNode(x,null);
back = back.next;
}
}
public void dequeue(){
if(isEmpty()){
return;
} else {
front = front.next;
}
}
}