Created
January 25, 2023 22:16
-
-
Save ChicagoDev/88c1add37545a9abe1876af0f4c99655 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/****************************************************************************** | |
* Compilation: javac FixedCapacityStackOfStrings.java | |
* Execution: java FixedCapacityStackOfStrings | |
* Dependencies: StdIn.java StdOut.java | |
* | |
* Stack of strings implementation with a fixed-size array. | |
* | |
* % more tobe.txt | |
* to be or not to - be - - that - - - is | |
* | |
* % java FixedCapacityStackOfStrings 5 < tobe.txt | |
* to be not that or be | |
* | |
* Remark: bare-bones implementation. Does not do repeated | |
* doubling or null out empty array entries to avoid loitering. | |
* | |
******************************************************************************/ | |
import edu.princeton.cs.algs4.StdIn; | |
import edu.princeton.cs.algs4.StdOut; | |
public class FixedCapacityStackOfStrings { | |
private String[] a; // holds the items | |
private int N; // number of items in stack | |
// create an empty stack with given capacity | |
public FixedCapacityStackOfStrings(int capacity) { | |
a = new String[capacity]; | |
N = 0; | |
} | |
public boolean isEmpty() { return N == 0; } | |
public boolean isFull() { return N == a.length; } | |
public void push(String item) { a[N++] = item; } | |
public String pop() { return a[--N]; } | |
public static void main(String[] args) { | |
int max = Integer.parseInt(args[0]); | |
FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max); | |
while (!StdIn.isEmpty()) { | |
String item = StdIn.readString(); | |
if (!item.equals("-")) stack.push(item); | |
else if (stack.isEmpty()) StdOut.println("BAD INPUT"); | |
else StdOut.print(stack.pop() + " "); | |
} | |
StdOut.println("\n"); | |
// print what's left on the stack | |
StdOut.print("Left on stack: "); | |
while (!stack.isEmpty()) { | |
StdOut.print(stack.pop() + " "); | |
} | |
StdOut.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment