Created
June 15, 2014 17:29
-
-
Save mbarinov/bb86173dfd953f499114 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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