// file:    StringListStack.java
// author:  Robert Keller
// purpose: Stack of Strings using List implementation
//
// StringListStack() constructor
// S.isEmpty()       tells whether S is empty.
// S.push(F)         push String F onto stack S.
// S.pop()           pop String from Stack S and return it

import java.io.PrintStream;

class StringListStack
{
private StringCell handle;	// pointer to the first cell in the list


StringListStack()		// constructor
  {
  handle = null;
  }


boolean isEmpty()		// check for emptiness
  {
  return handle == null;
  }


// create list with StringCell as its first cell

StringListStack(StringCell handle)
  {
  this.handle = handle;
  }


// mutating methods for Stack

// add a new first element to list, destructively changing this

void push(String s)
  {
  handle = new StringCell(s, handle);
  }


// remove first element and return it, destructively changing this

String pop()
  {
  String top = handle.first;
  handle = handle.rest;
  return top;
  }


// make a String representation of the list

public String toString()
  {
  StringBuffer b = new StringBuffer();
  StringCell C = this.handle;
  b.append("(");
  if( C != null )
    {
    b.append(C.first);
    C = C.rest;
    while( C != null )
      {
      b.append(" ");
      b.append(C.first);
      C = C.rest;
      }
    }
  b.append(")");
  return b.toString();
  }


// Test program

public static void main(String arg[])
  {
  System.out.println();
  System.out.println("S is a stack");

  StringListStack S = new StringListStack();

  System.out.println("S = " + S); 

  S.push("alpha");
  System.out.println("S = " + S); 

  S.push("beta");
  System.out.println("S = " + S); 

  S.push("gamma");
  System.out.println("S = " + S); 

  S.push("delta");
  System.out.println("S = " + S); 

  while( !S.isEmpty() )
    {
    System.out.println("S = " + S); 
    System.out.println("S.pop() = " + S.pop());
    }

  System.out.println("S = " + S);
  }
}


// StringCell is the building block for StringListStack

class StringCell
{
String first;
StringCell rest;

StringCell(String first, StringCell rest)
  {
  this.first = first;
  this.rest = rest;
  }
}


/* output of StringListStack.main

S is a stack
S = ()
S = (alpha)
S = (beta alpha)
S = (gamma beta alpha)
S = (delta gamma beta alpha)
S = (delta gamma beta alpha)
S.pop() = delta
S = (gamma beta alpha)
S.pop() = gamma
S = (beta alpha)
S.pop() = beta
S = (alpha)
S.pop() = alpha
S = ()

*/

