Princeton1/module4/src/main/java/com/hithomelabs/princeton1/module4/LinkedStack.java

73 lines
1.6 KiB
Java

package com.hithomelabs.princeton1.module4;
import java.util.Iterator;
// Creating a concrete linked Implementation of Stack
public class LinkedStack<E> extends Stack<E>{
// No need for an explicit constructor as size will be initialized to 0 and root to null
private int size;
private Node first;
// By default instance variables are package private
private class Node{
E value;
Node next;
}
// Will return true if size is 0
@Override
public boolean isEmpty() {
return (this.size == 0);
}
// Adds an element to the start of a linked list
@Override
public void push(E element) {
Node newNode = new Node();
newNode.value = element;
newNode.next = first;
first = newNode;
this.size = this.size + 1;
}
@Override
public E pop() {
if (this.isEmpty())
return null;
else{
Node toBePopped = first;
first = first.next;
this.size = this.size - 1;
return toBePopped.value;
}
}
@Override
public int size() {
return this.size;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
// Internal classes can access outer objects
Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public E next() {
E element = current.value;
current = current.next;
return element;
}
};
}
}