Guest User

Untitled

a guest
Jan 21st, 2018
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. public class Stack {
  2. private int size=0;
  3. private String[] q=new String[0];
  4. /** Adds a value to the top of the stack.*/
  5. public void push(String value){
  6. size++;
  7. String[] m=new String[size];
  8. m[0]=value;
  9. for(int x=1; x<size; x++){
  10. m[x]=q[x-1];
  11. }
  12. q=m;
  13. }
  14.  
  15. /** Removes the topmost string. If the stack is empty, returns null. */
  16. public String pop() {
  17. if(size==0)
  18. return null;
  19. else
  20. size--;
  21. String[] m=new String[size];
  22. String w = q[size];
  23. for(int x=0; x<size; x++){
  24. m[x]=q[x];
  25. }
  26. q=m;
  27. return w;
  28. }
  29.  
  30. /** Returns the topmost string but does not remove it. If the stack is empty, returns null. */
  31. public String peek() {
  32. if(isEmpty())
  33. return null;
  34. else
  35. return q[size-1];
  36. }
  37.  
  38. /** Returns true iff the stack is empty */
  39. public boolean isEmpty() {
  40. return (size==0);
  41. }
  42.  
  43. /** Returns the number of items in the stack. */
  44. public int length() {
  45. return size;
  46. }
  47.  
  48. /** Returns a string representation of the stack. Each string is separated by a newline. Returns an empty string if the stack is empty. */
  49. public String toString() {
  50. String s="";
  51. if(isEmpty())
  52. return s;
  53. for(int x=size-1; x>0; x--){
  54. s+=q[x]+"\n";
  55. }
  56. s+=q[0];
  57. return s;
  58. }
  59. }
Add Comment
Please, Sign In to add comment