Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. public class Stack<T> {
  2.  
  3. //Constructor
  4. Stack() {
  5. }
  6.  
  7. //String[] stackArray = new String[6]; //Array used for stack
  8. T[] stackArray = (T[]) new Object[6]; //Switched to Generic coding array type-casted to T[]
  9. int stackPointer = -1; //Starts at -1 to show stack is empty
  10. //Follows array index 0 being something is there
  11.  
  12. //Prints the stack
  13. public void printStack() {
  14.  
  15. for (int i = 0; i < stackArray.length; i++) {
  16.  
  17. if (i == 0 && stackArray[i] == null) { //Checks if stack is empty
  18. System.out.println("Stack is empty - Print Stack Function");
  19. break; //Break out of the for loop
  20. }
  21. else if (stackArray[i] == null ) { //Checks null values
  22. //Do nothing
  23. }
  24. else {
  25. System.out.println(stackArray[i]); //Displays if not null
  26. }
  27.  
  28. }
  29.  
  30. }
  31.  
  32. //Pushes an item onto the stack
  33. public void push(T item) {
  34.  
  35. // only proceed if the stack is not full
  36. if ( stackPointer < (stackArray.length - 1) ) {
  37. stackArray[stackPointer + 1] = item; //Push the item onto the stack
  38. stackPointer++; //Increment the stack pointer
  39. } else {
  40. System.out.println("Stack is full - Push Function"); //Print stack full message
  41. }
  42.  
  43. }
  44.  
  45. //Takes the last item out of the stack
  46. public T pop() {
  47.  
  48. T item; //The item to be returned by the pop method
  49.  
  50. if (stackPointer >= 0) { //Only proceed if the stack is not empty
  51. item = stackArray[stackPointer];
  52. stackArray[stackPointer] = null;
  53. stackPointer--;
  54. return item;
  55. }
  56. else {
  57. System.out.println("Stack is empty - Pop Function"); //Print empty stack method
  58. item = null;
  59. return item;
  60. }
  61.  
  62. }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement