JAVA现实栈类

栈遵循先进后出的规则。从栈放入项和从栈删除项的操作分别叫做压入(push)和弹出(pop)。除了push和pop操作,栈接口还应提供一个peek的操作用来查看栈的顶部。还应有常用的empty()和getSize()功能。下面针对int、double和char数据类型提供三个构建栈的类。

构建int型栈

public class StackOfInt {
	private int [] elements;
	private int size;
	public static final int DEFAULT_CAPACITY = 16;
	
	public StackOfInt(int capacity) {
		elements = new int [capacity];
	}
	
	public StackOfInt() {
		this(DEFAULT_CAPACITY);
	}
	
	public void push(int value) {
		if (size >= elements.length) {
			int [] temp = new int [2 * elements.length];
			System.arraycopy(elements, 0, temp, 0, elements.length);
			elements = temp;
		}
		elements [size ++] = value;
	}
	
	public int pop() {
		return elements [--size];
	}
	
	public int peek() {
		return elements [size - 1];
	}
	
	public boolean empty() {
		return size == 0;
	}
	
	public int getSize() {
		return size;
	}
}

构建double型栈


public class StackOfDouble {
	private double [] elements;
	private int size;
	public static final int DEFAULT_CAPACITY = 16;
	
	public StackOfDouble(int capacity) {
		elements = new double [capacity];
	}
	
	public StackOfDouble() {
		this(DEFAULT_CAPACITY);
	}
	
	public void push(double value) {
		if (size >= elements.length) {
			double [] temp = new double [2 * elements.length];
			System.arraycopy(elements, 0, temp, 0, elements.length);
			elements = temp;
		}
		elements [size ++] = value;
	}
	
	public double pop() {
		return elements [--size];
	}
	
	public double peek() {
		return elements [size - 1];
	}
	
	public boolean empty() {
		return size == 0;
	}
	
	public int getSize() {
		return size;
	}
}

构建char型栈:


public class StackOfChar {
	private char [] elements;
	private int size;
	public static final int DEFAULT_CAPACITY = 16;
	
	public StackOfChar(int capacity) {
		elements = new char [capacity];
	}
	
	public StackOfChar() {
		this(DEFAULT_CAPACITY);
	}
	
	public void push(char value) {
		if (size >= elements.length) {
			char [] temp = new char [2 * elements.length];
			System.arraycopy(elements, 0, temp, 0, elements.length);
			elements = temp;
		}
		elements [size ++] = value;
	}
	
	public char pop() {
		return elements [--size];
	}
	
	public char peek() {
		return elements [size - 1];
	}
	
	public boolean empty() {
		return size == 0;
	}
	
	public int getSize() {
		return size;
	}
}

 

你可能感兴趣的:(JAVA现实栈类)