22 01ContiguousStacks
22 01ContiguousStacks
Prepared by:
Waleed A. Yousef, Ph.D.
S
Push box Q onto stack: Q Push box S onto stack: Q
D Q
Q Q
void ReverseRead(void){
StackEntry item;//StackEntry should be defined as char
Stack stack;
CreateStack(&stack);//Initialize the stack to be empty
while (!StackEmpty(&stack)){
Pop(&item, &stack); //Pop an item from the stack.
putchar(item);
}
putchar('\n');
}
© Waleed A. Yousef 2008 6
Again: Information hiding (Encapsulation):
MAXSTACK-1 CreateStack(s);
top -2580 0
entry }
s
When we return:
MAXSTACK-1
top -2580 0
entry
© Waleed A. Yousef 2008 s 11
Implementation level But this way User Level
(what really happens) (interface)
void CreateStack(Stack *ps){ void main(){
ps->top=0;
} Stack s;
CreateStack(&s);
CreateStack
&s }
ps When we return:
The execution time does
not depend on n;
MAXSTACK-1 therefore the complexity
is: (1)
top -2580 0
entry top is the index of the
© Waleed A. Yousef 2008
s first available place. 12
Implementation level User Level
(what really happens) (interface)
void Push(StackEntry e, Stack *ps){
ps->entry[ps->top]=e;
ps->entry[ps->top++]=e;
ps->top++;
}
void main(){
Push StackEntry e;
Stack s;
e &s
ps CreateStack(&s);
Push(e, &s);
MAXSTACK-1
}
top 0
1 0 e
entry
Stack s;
MAXSTACK-1
CreateStack(&s);
.
.
top 0 TraverseStack(&s, &Display);
entry }
s //&s only for efficiency as
© Waleed A. Yousef 2008 said before. 22
Exercise: How to write the function StackTop in the user level? (e.g.,
if you do not have the source code of the implementation)
User Level:
void StackTop(StackEntry *pe, Stack *ps){
Pop(pe, ps); /* Why interface, Pre, Post are crucial:
Push(*pe, ps); Pop takes a pointer to the element and a
} pointer to the stack.
###
e
MAXSTACK-1
top 1
0 0 ###
entry
So, the main file will compile even if stack.cpp is not compiled
yet. (check the homework; this is detailed in the sheet)