Stack Sample Program


import java.util.Scanner;

public class StackReverseWords {
   public static void main(String[] args) {
      Scanner stdin = new Scanner(System.in);

      StackInterface<String> stringStack;
      stringStack = new ArrayBoundedStack<String>();

      String line;
      String[] words;

// read in a line of text, split it into words
      System.out.print("Enter a line of text==> ");
      line = stdin.nextLine();
      words = line.split("\\s+");

// print the words and push them onto a stack
      for (int i = 0 ; i < words.length ; i++) {
		 System.out.println(words[i]);
         stringStack.push(words[i]);
      }

// pop the words and print them
      System.out.println("\nReverse is:\n");
      while (!stringStack.isEmpty()) {
         line = stringStack.top();
         stringStack.pop();
         System.out.println(line);
      }
   }
}

Sample Output

Enter a line of text==> the    road goes   ever  on and    on
the
road
goes
ever
on
and
on

Reverse is:

on
and
on
ever
goes
road
the


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2020