L9 Stack ImplementationArrays
L9 Stack ImplementationArrays
Array Implementation
struct STACK{
inforec i; // could be any type of item i.e an int
int top;
};
Stacks
Function’s definition:
create_stack(s).
empty(s)
pop(s, i)
top(s, i)
push(s, i)
purge(s)
Toolkit function
Toolkit function
A function that can access the data structure
directly that represent the ADT.
A reusable functions. (can be used in many
programs ).
Save programming time.
Make the program more readable
Not aToolkit function
A function for an ADT that can NOT directly
access the data structure directly that
represent the ADT, it can ONLY call the
Toolkit function.
Example of a ToolKit function
Void push(stack & S, const INFOREC & i)
{
++S.top; //directly access the data structure
S.i[S,top] = i;
}
Example of a NON ToolKit
function
Void Remove_Secondpush(stack & s, INFOREC & item)
{
INFOREC temp;
pop(s, temp1);
pop(s, item2); // no direct accessed to the data structure, only calls are made to tool kit
functions
push(s, temp1);
}
Create a stack
Given:
struct inforec{
int number;
s)
};
k & L;
ac UL
struct Stack{
st N
inforec i[SIZE];
ck( = -1
int top; ta { op =
s t
s. top
};
at_
Stack s;
re s .
// initializes top to null and count to 0; c //
void creat_stack(stack & s) oid
{
v }
s.top = -1;
count =0;
}
// also can be written as
void creat_stack(stack & s)
{
s.top = NULL;
count =0;
}
//OR
void creat_stack(stack & s)
{
s.top = NULL; // s.top = -1
A function to check if the stack is
empty
Given:
struct Stack{
inforec i; // could be any type of data typei.e an int
int top;
};
int empty(constant Stack & s)
{
return ( s.top = = -1);
}
Note: purging a stack requires the release and return of all nodes to the
heap, more to cover with linked list and pointer… later
Interchanging top 2 items in a
stack
Void interchange_top_2(STACK &S)
{
INFO_REC item1, item2;
pop(S, item1);
pop(S,item2);
push(S,item1);
push(S,item2);
}
Array Implementation
Stacks in JAVA
Array Implementation of Stacks
int [ ] s;
int top; // points to actual end of the stack
A constructor in Java is a
Constructor: block of code similar to a
method that's called when an
ArrayStack(int capacity)
instance of an object is created.
{
s = new int[capacity]; the key differences between a
top = 0; constructor and a method: A
} constructor doesn't have a
return type. ... Unlike methods,
constructors are not
considered members of a class.
Array Implementation of a Stack
int pop()
{
if (top == 0)
{then throw new
IllegalStateException();}
top --;
s[top];
}
Stack Overflow and Underflow
boolean empty()
{
return top == 0;
}
Peek()
To return the item currently at the “top” of the
stack:
int peek()
{
if (top ==0 )
{ new IllegalStateException(); }
return s[top-1];
}
Array-Based Stacks of Other Types
Implementing stacks of other types is similar to
implementing a stack of int.
s[top-1] = null;