Java 实例 - 栈的实现

以下实例演示了用户如何通过创建用于插入元素的自定义函数 push() 方法和用于弹出元素的 pop() 方法来实现栈:

MyStack.java 文件

  1. public class MyStack {
  2. private int maxSize;
  3. private long[] stackArray;
  4. private int top;
  5. public MyStack(int s) {
  6. maxSize = s;
  7. stackArray = new long[maxSize];
  8. top = -1;
  9. }
  10. public void push(long j) {
  11. stackArray[++top] = j;
  12. }
  13. public long pop() {
  14. return stackArray[top--];
  15. }
  16. public long peek() {
  17. return stackArray[top];
  18. }
  19. public boolean isEmpty() {
  20. return (top == -1);
  21. }
  22. public boolean isFull() {
  23. return (top == maxSize - 1);
  24. }
  25. public static void main(String[] args) {
  26. MyStack theStack = new MyStack(10);
  27. theStack.push(10);
  28. theStack.push(20);
  29. theStack.push(30);
  30. theStack.push(40);
  31. theStack.push(50);
  32. while (!theStack.isEmpty()) {
  33. long value = theStack.pop();
  34. System.out.print(value);
  35. System.out.print(" ");
  36. }
  37. System.out.println("");
  38. }
  39. }

以上代码运行输出结果为:

  1. 50 40 30 20 10