Stack的简单应用

栈(Stack)的简单应用:

构建Stack,接口方法有push(), pop(), peek(), isEmpty()等,使用LinkedList来创建Stack,如下:

class Stack<T> {
	private LinkedList<T> list = new LinkedList<T>();
	public void push(T elem) {
		list.addFirst(elem);
	}
	
	public T pop() {
		return list.removeFirst();
	}
	
	public T peek() {
		return list.getFirst();
	}
	
	public boolean isEmpty() {
		return list.isEmpty();
	}
	
	public String toString() {
		return list.toString();
	}
}

以字符串简单测试下:

public class stackTest {
	static public void main(String[] args) {
		boolean bPushElem = false;
		Stack<String> stack1 = new Stack<String>();
		String originStr = "+U+n+c---+e+r+t---+a-+i-+n+t+y---+~-+r+u--+l+e+s";
		System.out.println(originStr);
		
		for (String s: originStr.split("")) {	
			if (s.equals("+")) {
				bPushElem = true;
				continue;
			} else if(s.equals("-")) {
				stack1.pop();
				System.out.println(stack1);
			} else if (s.equals(" ")) {
				continue;
			} else {
				if (bPushElem) {
					stack1.push(s);
					System.out.println(stack1);
				}
				bPushElem = false;
			}
		}
		System.out.println(stack1);
	}
}


你可能感兴趣的:(Stack的简单应用)