edu.uci.qa.performancedriver.util.LinkedStack Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of performancedriver Show documentation
Show all versions of performancedriver Show documentation
A performance measuring API with high performance and portability
The newest version!
package edu.uci.qa.performancedriver.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedStack implements Iterable, Cloneable {
private int size;
private Node first;
private class Node {
private V value;
private Node next;
public Node(V value) {
this(value, null);
}
public Node(V value, Node next) {
this.value = value;
this.next = next;
}
}
public LinkedStack() {
this.first = null;
this.size = 0;
}
public LinkedStack(LinkedStack other) {
this();
if (other.isEmpty()) {
return;
}
first = new Node(other.first.value);
for (Node prev = first, temp = other.first.next; temp != null;
temp = temp.next, prev = prev.next) {
prev.next = new Node(temp.value);
}
this.size = other.size;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return size;
}
public void push(V value) {
first = new Node(value, first);
size++;
}
public V pop() {
if (isEmpty()) {
throw new NoSuchElementException("Stack Underflow");
}
V value = first.value;
first = first.next;
size--;
return value;
}
public final V peek() {
if (isEmpty()) {
throw new NoSuchElementException("Stack Underflow");
}
return first.value;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (V v : this) {
sb.append(v + " ");
}
return sb.toString();
}
@Override
protected LinkedStack clone() {
return new LinkedStack<>(this);
}
@Override
public Iterator iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator {
private Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
V value = current.value;
current = current.next;
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}