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);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章