# Data structure and algorithm 10 - stack and queue

Keywords: Java

Stacks are usually very small because they are temporary storage

StackX method:

The construction method creates a new stack according to the capacity specified by the parameters. The domain of the stack includes variables representing the maximum capacity. The array itself and the variable top store the subscript of the top element of the stack.

push() method:

Increase top by one, so that it points to a position above the original top data item. And store a data item in this location. Again, top is incremented before inserting data items.

pop() method:

Return the data item value identified by top, and then subtract one from top.

``````
class StackX {
private int maxSize;
private long[] stackArray;
private int top;
public StackX(int s)
{
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j)
{
stackArray[++top] = j;
}
public long pop()
{
return stackArray[top--];
}
public long peek()
{
return stackArray[top];
}
public boolean isEmpty()
{
return (top == -1);
}
public boolean isFull() {
return (top == maxSize-1);
}
}
class StackApp
{
public static void main(String[] args) {
StackX theStack = new StackX(10);
theStack.push(10);
theStack.push(20);
theStack.push(30);
theStack.push(40);
while(!theStack.isEmpty())
{
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("end");
}
}
``````
``40 30 20 10 end``

Reverse word order:

``````import java.io.BufferedReader;
import java.io.IOException;

class StackX1 {
private int maxSize;
private long[] stackArray;
private int top;
public StackX1(int s)
{
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j)
{
stackArray[++top] = j;
}
public long pop()
{
return stackArray[top--];
}
public long peek()
{
return stackArray[top];
}
public boolean isEmpty()
{
return (top == -1);
}
public boolean isFull() {
return (top == maxSize-1);
}
}
class Reverser
{
private String input;
private String output;
public Reverser(String in)
{
input = in;
}
public String doRev()
{
int StackSize = input.length();
StackX1 theStack = new StackX1(StackSize);
for(int j=0;j<input.length();j++)
{
char ch = input.charAt(j);
theStack.push(ch);
}
output = " ";
while(!theStack.isEmpty())
{
char ch = (char) theStack.pop();
output = output + ch;
}
return output;
}
}
class ReverseApp
{
public static void main(String[] args) throws IOException {
String input,output;
while(true)
{
System.out.print("enter");
System.out.flush();
input = getString();
if(input.equals(" "))
break;
Reverser theReverser = new Reverser(input);
output = theReverser.doRev();
System.out.println(output);
}
}

private static String getString() throws IOException{
// TODO Auto-generated method stub
``````enter kdjfklajkfaj