【学习笔记】Stacks

198 阅读1分钟

A stack is a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle.
Java里面有java.util.Stack类,但Java文档建议不要使用这个类,建议使用Deque(因为Deque同时具有Queue和Stack的功能?)。

Stack Interface

public interface Stack<E> {
	int size();    // return the number of elements in the stack 
	boolean isEmpty(); 

	void push(E e); 
	E top();      // Returns, but does not remove, the element at the top of the stack
	E pop();      // Removes and returns the top element from the stack
}

Array-based Stack Implementation

public class ArrayStack<E> implements Stack<E> {
	public static final int CAPACITY = 1000; 
	private E[] data; 
	private int t = -1;        // index of the top element in stack
	public ArrayStack() { this(CAPACITY); } 
	public ArrayStack(int capacity) { 
		data = (E[]) new Object[capacity]; 
	}
	public int size() { return (t + 1); } 
	public boolean isEmpty() { return (t == -1); } 
	public void push(E e) throws IllegalStateException {
		if(size() == data.length) throw new IllegalStateException("Stack is full"); 
		data[++t] = e;      // increment t before storing new item
	}
	public E top() {
		if(isEmpty()) return null; 
		return data[t]; 
	}
	public E pop() {
		if(isEmpty()) return null; 
		E answer = data[t]; 
		data[t] = null;       // deference to help garbage collection
		t--; 
		return answer; 
	}
}

Implementing a Stack with a Singly Linked List

In the implementation, the top of the stack is at the front of the list.

public class LinkedStack<E> implements Stack<E> {
	private SinglyLinkedList<E> list = new SinglyLinkedList<>(); 
	public LinkedStack() {}      // new stack relies on the initially empty list
	public int size() { return list.size(); } 
	public boolean isEmpty() { return list.isEmpty(); } 
	public void push(E element) { list.addFirst(element); } 
	public E top() { return list.first(); } 
	public E top() { return list.removeFirst(); } 
}

Reversing an Array Using a Stack

public class ReverseArray() {
	// A generic method for reversing an array 
	public static <E> void reverse(E[] a) {
		Stack<E> buffer = new ArrayStack<>(a.length); 
		for(int i = 0; i < a.length; i++) buffer.push(a[i]); 
		for(int j = 0; j < a.length; j++) a[i] = buffer.pop(); 
	}

	public static void main(String[] args) {
		Integer[] a = {4, 8, 15, 16, 23, 42};       // Autoboxing
		String[] s = {"Jack", "Kate", "Hurley", "Jin", "Michael"}; 
		System.out.println("a = " + Arrays.toString(a)); 
		System.out.println("s = " + Arrays.toString(s)); 
		System.out.println("Reversing..."); 
		reverse(a); 
		reverse(s); 
		System.out.println("a = " + Arrays.toString(a)); 
		System.out.println("s = " + Arrays.toString(s)); 
	}
}