Stack(LIFO) implementation in java (linkedlist)
A stack is a collection that is based on the last-in-first-out (LIFO) policy.
- push() - push an item into stack.
- pop() - get an item and remove it from the top.
(This Stack implementation is based on a linked-list data structure)
- public class Stack<Item> implements Iterable<Item>
- {
- // top of stack (most recently added node)
- private Node first;
- // number of items
- private int N;
- private class Node
- {
- Item item;
- Node next;
- }
- public boolean isEmpty() { return first == null; } // Or: N == 0.
- public int size() { return N; }
- // Add item to top of stack.
- public void push(Item item)
- {
- Node oldfirst = first;
- first = new Node();
- first.item = item;
- first.next = oldfirst;
- N++;
- }
- public Item pop()
- { // Remove item from top of stack.
- Item item = first.item;
- first = first.next;
- N--;
- return item;
- }
- }
Comments
Post a Comment