J.E.D.I
2.4 Sequential Representation
Sequential allocation of stack makes use of arrays, hence the size is static. The stack is empty if the top=-1 and full if top=n-1. Deletion from an empty stack causes an
underflow while insertion onto a full stack causes an overflow. The following figure shows an example of the ADT stack:
Figure 1.9 Deletion and Insertion
The following is the Java implementation of stack using sequential representation: public class ArrayStack implements Stack{
Default length of the array public static final int CAPACITY = 1000;
Length of the array used to implement the stack public int capacity;
Array used to implement the stack Object S[];
Initializes the stack to empty int top = -1;
Initialize the stack to default CAPACITY public ArrayStack{
thisCAPACITY; }
Initialize the stack to be of the given length public ArrayStackint c{
capacity = c; S = new Object[capacity];
} Implementation of size
public int size{ return top+1;
} Implementation of isEmpty
public boolean isEmpty{ return top 0;
Data Structures 24
J.E.D.I
} Implementation of top
public Object top{ if isEmpty throw new
StackExceptionStack empty.; return S[top];
} Implementation of pop
public Object pop{ Object item;
if isEmpty throw new StackExceptionStack underflow.;
item = S[top]; S[top--] = null;
return item; }
Implementation of push public void pushObject item{
if size==capacity throw new StackExceptionStack overflow.;
S[++top]=item; }
}
2.5 Linked Representation
A linked list of stack nodes could be used to implement a stack. In linked representation, a node with the structure defined in lesson 1 will be used:
class Node{ Object info;
Node link; }
The following figure shows a stack represented as a linked linear list:
Figure 1.10 Linked Representation The following Java code implements the ADT stack using linked representation:
public class LinkedStack implements Stack{ private Node top;
Data Structures 25
J.E.D.I
The number of elements in the stack private int numElements = 0;
Implementation of size public int size{
return numElements; }
Implementation of isEmpty public boolean isEmpty{
return top == null; }
Implementation of top public Object top{
if isEmpty throw new StackExceptionStack empty.;
return top.info; }
Implementation of pop public Object pop{
Node temp; if isEmpty
throw new StackExceptionStack underflow.; temp = top;
top = top.link; return temp.info;
} Implementation of push
public void pushObject item{ Node newNode = new Node;
newNode.info = item; newNode.link = top;
top = newNode;
} }
2.6 Sample Application: Pattern Recognition Problem