Question: Modify the code of Figure 4.18 to support storing variable-length strings of at most 255 characters. The stack array should have type char. A string
Modify the code of Figure 4.18 to support storing variable-length strings of at most 255 characters.

The stack array should have type char. A string is represented by a series of characters (one character per stack element), with the length of the string stored in the stack element immediately above the string itself, as illustrated by Figure 4.32.

The push operation would store an element requiring i storage units in the i positions beginning with the current value of top and store the size in the position i storage units above top.
The value of top would then be reset above the newly inserted element. The pop operation need only look at the size value stored in position top - 1 and then pop off the appropriate number of units. You may store the string on the stack in reverse order if you prefer, provided that when it is popped from the stack, it is returned in its proper order.
/** Array-based stack implementation */ class AStack implements Stack { private static final int defaultSize = 10; private int maxSize; private int top; private E [] listArray; // Constructors Astack() { this (defaultSize); } @SuppressWarnings ("unchecked") // Generic array allocation AStack (int size) { } public void clear() { top = 0; } public void push (E it) { assert top != maxSize: listArray [top++] = it; } // Maximum size of stack // Index for top Object // Array holding stack maxSize = size; top = 0; listArray (E[]) new Object [size]; // Create listArray } } // Reinitialize stack public E pop() { assert top != 0: "Stack is empty"; return listArray [--top]; // Push "it" onto stack "Stack is full"; // Pop top element public E topValue () { assert top != 0: "Stack is empty"; return listArray [top-1]; // Return top element // Return length Figure 4.18 Array-based stack class implementation. public int length() { return top;}
Step by Step Solution
3.46 Rating (153 Votes )
There are 3 Steps involved in it
To adapt the provided code Figure 418 to support storing variablelength strings of at most 255 characters we need to make several modifications 1 Change the stack array to have a type of c h a r c h a ... View full answer
Get step-by-step solutions from verified subject matter experts
