Advertisement
ibragimova_mariam

Stack

Dec 14th, 2020
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. /*
  2. GENERAL TASK DESCRIPTION
  3.  
  4. Implement barebones (meaning - no getters/setters, or anything extraneous
  5. In task descriptions after data structure name the required interface (list of public methods) is in parentheses
  6. Use proper formatting. Implement each data structure in a separate class. For Node classes use inner classes.
  7. For brevity use primitive integer as value type (no generics).
  8. */
  9.  
  10. // Task 1 - singly-linked list (add, get, remove) add(), get(i), remove(i), remove(O)
  11.  
  12. // Task 2 - stack (push, pop)
  13.  
  14. // Task 3 - queue (offer, poll)
  15.  
  16. // Task 4 - flexible-size list (using arrays - think of ArrayList) - (add, get, remove, insert)
  17.  
  18.  
  19. class Stack {
  20. private Node last;
  21.  
  22. public void push(Integer value) {
  23.  
  24. if (last == null)
  25. last = new Node(value, null);
  26. else {
  27. Node node = new Node(value, last);
  28. last = node;
  29. }
  30. }
  31.  
  32. public Integer pop() { // get should return the value, not the node
  33.  
  34. if (last == null)
  35. throw new IllegalStateException();
  36.  
  37. Node node = last;
  38. last = last.next;
  39.  
  40. return node.value;
  41. }
  42.  
  43. public Integer top() {
  44.  
  45. if (last == null)
  46. throw new IllegalStateException();
  47.  
  48. return last.value;
  49. }
  50.  
  51. public boolean empty() {
  52. return last == null;
  53. }
  54.  
  55. static class Node {
  56. public Integer value;
  57. public Node next;
  58.  
  59. Node(Integer value, Node next) {
  60. this.value = value;
  61. this.next = next;
  62. }
  63. }
  64.  
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement