desislava_topuzakova

Untitled

Jun 17th, 2021
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. import java.util.Iterator;
  2.  
  3. public class Stack<Integer> implements Iterable<Integer> {
  4. private Node<Integer> top;
  5.  
  6. public Stack() {
  7. this.top = null;
  8. }
  9.  
  10. //push
  11. public void push(int newElement) {
  12. Node<Integer> newNode = new Node<>(newElement);
  13. newNode.prev = this.top;
  14. this.top = newNode;
  15. }
  16.  
  17. //pop
  18. public int pop() {
  19. if (this.top == null) {
  20. System.out.println("No elements");
  21. return 0;
  22. } else {
  23. Node<Integer> currentTop = this.top;
  24. this.top = this.top.prev;
  25. return currentTop.element;
  26. }
  27. }
  28.  
  29. @Override
  30. public Iterator<Integer> iterator() {
  31. return new Iterator<Integer> () {
  32. private Node<Integer> current = top;
  33.  
  34. @Override
  35. public boolean hasNext() {
  36. return current != null;
  37. }
  38.  
  39. @Override
  40. public Integer next() {
  41. int currentValue = current.element;
  42. this.current = this.current.prev;
  43. return (Integer) java.lang.Integer.valueOf(currentValue);
  44. }
  45. };
  46. }
  47. }
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment