StringBuilder sb = new StringBuilder("[");
for (int i = size - 1; i > -1; i--) {
sb.append(elementData[i].toString() + ", ");
}
int len = sb.length();
return sb.delete(len - 2, len).append("]").toString();
}
}
}
测试类:
package com.ietree.basic.datastructure.stack;
/**
* Created by ietree
* 2017/4/29
*/
public class SequenceStackTest {
public static void main(String[] args) {
SequenceStack<String> stack = new SequenceStack<String>();
stack.push("aaaa");
stack.push("bbbb");
stack.push("cccc");
stack.push("dddd");
System.out.println(stack);
System.out.println("访问栈顶元素:" + stack.peek());
System.out.println("第一次弹出栈顶元素:" + stack.pop());
System.out.println("第二次弹出栈顶元素:" + stack.pop());
System.out.println("两次pop之后的栈:" + stack);
}
}
程序输出:
[dddd, cccc, bbbb, aaaa]
访问栈顶元素:dddd
第一次弹出栈顶元素:dddd
第二次弹出栈顶元素:cccc
两次pop之后的栈:[bbbb, aaaa]