Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Alice

StackExample


LinkedStack.java

import java.util.*;

/**
 * A simple Stack implementation based on a linked list
 * 
 * @author Chuck Cusack
 * @version 1.0, February 2008
 */
public class LinkedStack<T> implements StackInterface<T>
{
    Node<T> top;

    /**
     * Constructor for objects of class LinkedStack
     */
    public LinkedStack()
    {
        // For simplicity, we will use a dummy node.
        top=new Node<T>();
        top.setNext(null);
    }

    public boolean isEmpty() {
        return top.getNext()==null;
    }
    
    public boolean isFull() {
        return false;
    }
    
    public boolean push(T item) {
        Node<T> newTop = new Node<T>(item,top.getNext());
        top.setNext(newTop);
        return true;
    }
    public T pop() {
        if(isEmpty()) {
            return null;
        } else {
            T key = top.getNext().getKey();
            top.setNext(top.getNext().getNext());
            return key;
        }
    } 
    public T peek() {
        if(isEmpty()) {
            return null;
        } else {
            return top.getNext().getKey();
        }
    }
    public Iterator<T> iterator() {
        // We pass top.next() because top is a dummy node.
        return new NodeIterator(top.getNext());
    }
}