Item
- the generic type of an item in this stackpublic class Stack<Item>
extends Object
implements Iterable<Item>
Stack
class represents a last-in-first-out (LIFO) stack of generic items.
It supports the usual push and pop operations, along with methods
for peeking at the top item, testing if the stack is empty, getting the number of
items in the stack, and iterating over the items in LIFO order.
This implementation uses a singly-linked list with a nested class for linked-list nodes. The push, pop, peek, size, and is-empty operations all take constant time in the worst case.
For additional documentation, see Section 4.3 of Computer Science: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne.
Constructor and Description |
---|
Stack()
Initializes an empty stack.
|
Modifier and Type | Method and Description |
---|---|
boolean |
isEmpty()
Returns true if this stack is empty.
|
java.util.Iterator<Item> |
iterator()
Returns an iterator to this stack that iterates through the items in LIFO order.
|
static void |
main(String[] args)
Unit tests the
Stack data type. |
Item |
peek()
Returns (but does not remove) the item most recently added to this stack.
|
Item |
pop()
Removes and returns the item most recently added to this stack.
|
void |
push(Item item)
Adds the item to this stack.
|
int |
size()
Returns the number of items in this stack.
|
String |
toString()
Returns a string representation of this stack.
|
public boolean isEmpty()
public int size()
public void push(Item item)
item
- the item to addpublic Item pop()
java.util.NoSuchElementException
- if this stack is emptypublic Item peek()
java.util.NoSuchElementException
- if this stack is emptypublic String toString()
toString
in class Object
public java.util.Iterator<Item> iterator()
iterator
in interface Iterable<Item>
public static void main(String[] args)
Stack
data type.args
- the command-line arguments