Guest User

Untitled

a guest
Feb 24th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. package Containers;
  2.  
  3. import org.jetbrains.annotations.NotNull;
  4.  
  5. import java.util.Iterator;
  6. import java.util.NoSuchElementException;
  7.  
  8. public class Stack<Item> implements Iterable<Item> {
  9. private int size;
  10. private Node first;
  11.  
  12. private class Node{
  13. private Item item;
  14. private Node next;
  15. }
  16.  
  17. private class MyIterator implements Iterator<Item> {
  18. private Node current = first;
  19.  
  20. @Override
  21. public boolean hasNext() {
  22. return current != null;
  23. }
  24.  
  25. @Override
  26. public Item next() {
  27. if (!hasNext()) {
  28. throw new NoSuchElementException();
  29. }
  30.  
  31. Item item = current.item;
  32. current = current.next;
  33.  
  34. return item;
  35. }
  36.  
  37. @Override
  38. public void remove() {
  39. throw new UnsupportedOperationException();
  40. }
  41. }
  42.  
  43. @NotNull
  44. public Iterator<Item> iterator() {
  45. return new MyIterator();
  46. }
  47.  
  48. public Stack() {
  49. first = null;
  50. size = 0;
  51. }
  52.  
  53. public int getSize() {
  54. return size;
  55. }
  56.  
  57. public boolean isEmpty() {
  58. return first == null;
  59. }
  60.  
  61. public void push(Item item) {
  62. Node previousItem = first;
  63. first = new Node();
  64. first.item = item;
  65. first.next = previousItem;
  66. size++;
  67. }
  68.  
  69. public Item pop() {
  70. if (isEmpty()){
  71. throw new IndexOutOfBoundsException("Stack is empty");
  72. }
  73.  
  74. Item item = first.item;
  75. first = first.next;
  76. size--;
  77.  
  78. return item;
  79. }
  80.  
  81. public Item peek() {
  82. if (isEmpty()){
  83. throw new IndexOutOfBoundsException("Stack is empty");
  84. }
  85.  
  86. return first.item;
  87. }
  88.  
  89. @Override
  90. public String toString() {
  91. StringBuilder builder = new StringBuilder("Stack [");
  92.  
  93. for (Item item : this) {
  94. builder.append(item);
  95. builder.append(' ');
  96. }
  97.  
  98. builder.append("]\n");
  99. builder.append("Size: ").append(size);
  100.  
  101. return builder.toString();
  102. }
  103. }
Add Comment
Please, Sign In to add comment