Advertisement
desislava_topuzakova

03. Stack Iterator - Stack

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