Skip to content

Instantly share code, notes, and snippets.

@mbarinov
Created June 15, 2014 17:29
Show Gist options
  • Save mbarinov/bb86173dfd953f499114 to your computer and use it in GitHub Desktop.
Save mbarinov/bb86173dfd953f499114 to your computer and use it in GitHub Desktop.
import edu.princeton.cs.introcs.StdOut;
import java.util.Arrays;
import java.util.Iterator;
class LinkedStack<T> implements Iterable<T> {
private Node first;
private int N;
private class Node {
T value;
Node next;
}
public T pop() {
T value = first.value;
first = first.next;
return value;
}
public void push(T item) {
Node oldFirst = first;
first = new Node();
first.value = item;
first.next = oldFirst;
N++;
}
public Iterator<T> iterator() {
return new StackIterator();
}
private class StackIterator implements Iterator<T> {
private int i = N;
private Node current = first;
public T next() {
T item = current.value;
current = current.next;
return item;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
}
}
}
class test {
public static void main(String[] args) {
LinkedStack<Integer> stack = new LinkedStack<Integer>();
stack.push(2);
stack.push(3);
stack.push(4);
int result = stack.pop();
StdOut.print(result);
for (int t : stack) {
StdOut.print(t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment