You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.4 KiB

6 years ago
  1. // The CharStack class that implements a stack of characters
  2. // Xiwei Wang
  3. public class CharStack
  4. {
  5. // instance variables
  6. private char[] m_array;
  7. private int m_index;
  8. // constructor
  9. public CharStack(int cap)
  10. {
  11. m_array = new char[cap];
  12. m_index = 0;
  13. }
  14. // check whether the stack is empty
  15. public boolean isEmpty()
  16. {
  17. if (m_index == 0)
  18. return true;
  19. else
  20. return false;
  21. }
  22. // return the element at the top of the stack
  23. public char top()
  24. {
  25. if (isEmpty())
  26. throw new RuntimeException("top attempted on an empty stack");
  27. else
  28. return m_array[m_index - 1];
  29. }
  30. // push a character onto the stack
  31. public void push(char c)
  32. {
  33. m_array[m_index] = c;
  34. m_index++;
  35. }
  36. // remove and return the element at the top of the stack
  37. public char pop()
  38. {
  39. if (isEmpty())
  40. throw new RuntimeException("pop attempted on an empty stack");
  41. else
  42. {
  43. char c = m_array[m_index - 1];
  44. m_index--;
  45. return c;
  46. }
  47. }
  48. // return the size of the stack
  49. @Override
  50. public String toString()
  51. {
  52. String stackContent = "";
  53. for (int i = m_index - 1; i >= 0; i--)
  54. stackContent += m_array[i];
  55. return stackContent;
  56. }
  57. }