0% found this document useful (0 votes)
9 views3 pages

Class ArrayStack

The ArrayStack class implements a generic stack using an array to store elements, with an initial capacity of 10. It provides methods to push, pop, and peek at elements, as well as to check if the stack is empty and to reallocate memory when the stack is full. The class also includes a copy constructor for creating a new stack based on an existing one.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views3 pages

Class ArrayStack

The ArrayStack class implements a generic stack using an array to store elements, with an initial capacity of 10. It provides methods to push, pop, and peek at elements, as well as to check if the stack is empty and to reallocate memory when the stack is full. The class also includes a copy constructor for creating a new stack based on an existing one.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

class ArrayStack<E>

// Data Fields

private E[ ] theData; // array to store stack elements

/** Index of top of the stack. */

private int topOfStack; // index of stack top.

private static final int INITIAL_CAPACITY = 10;

/**

* Construct an empty stack with the default initial capacity.

*/

public ArrayStack()

topOfStack = -1; // Initially empty stack.

theData = (E[]) new Object[INITIAL_CAPACITY];

public ArrayStack(int cap)

topOfStack = -1; // Initially empty stack.

if (cap <= 0 )

cap = INITIAL_CAPACITY;

theData = (E[]) new Object[cap];

public ArrayStack (ArrayStack<E> other)

{
theData = (E[]) new Object[[Link] + 1];

for (int i = 0; i < [Link] + 1; i++)

theData[i]= [Link][i];

topOfStack = [Link];

public E push(E obj)

if (topOfStack == [Link] - 1) {

reallocate();

topOfStack++;

theData[topOfStack] = obj;

return obj;

public E pop()

if (isEmpty()) {

throw new NoSuchElementException();

E result = theData[topOfStack];

theData[topOfStack] = null;

topOfStack--;

return result;

}
public E peek()

if (isEmpty()) {

throw new NoSuchElementException();

return theData[topOfStack];

/**

* Return true if the stack is empty

* @return True if the stack is empty

*/

public boolean isEmpty()

return (topOfStack == -1);

private void reallocate() {

E[] temp = (E[]) new Object[2 * [Link]];

[Link](theData, 0, temp, 0, [Link]);

theData = temp;

} //end ArrayStack

You might also like