Java 实例 - 栈的实现


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

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

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

  1. 50 40 30 20 10