// Decode.java from Lewis and Loftus, page 508, modified to // demonstrate user-defined stack implemeted as a linked list. import java.io.*; // Each node of a Stack object contains a Character data and a // reference to the next node. Initially, the stack is defined // by a reference to the "top" node. class Stack { private StackNode top; public Stack () { top = null; } public void push (Character nextChar) { StackNode node = new StackNode (nextChar); node.next = top; top = node; } public Character pop () { Character data = top.letter; top = top.next; return data; } public boolean empty () { return (top == null); } public String toString () { String result = ""; StackNode current = top; while (current != null) { result += current.letter.toString(); current = current.next; } return result; } // An inner class that represents a node in the Stack private class StackNode { public Character letter; public StackNode next; public StackNode (Character nextLetter) { letter = nextLetter; next = null; } } } public class MyDecode { public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Stack word = new Stack(); String message; int index = 0; System.out.println ("Enter the coded message:"); message = stdin.readLine(); System.out.println ("The decoded message is:"); while (index < message.length()) { while (index < message.length() && message.charAt(index) != ' ') { word.push (new Character(message.charAt(index))); index++; } // Print current word in reverse order while (!word.empty()) System.out.print (((Character)word.pop()).charValue()); System.out.print (" "); index++; } System.out.println(); } }