Java栈之顺序栈存储结构实现(2)

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]

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/4e776bcdd7b4bf493302710fa5bd04b0.html