7. Stack: ADT List
Implementation, Creation/Insertion
void push (int value)
{
Node *ptr = new Node();
ptr->data = value;
ptr->next = top;
top = ptr;
}
8. Stack: ADT List
Implementation, Deletion
void pop ( )
{
if ( isempty() )
cout<<"Stack is Empty";
else
{
Node *ptr = top;
top = top -> next;
delete(ptr); }}
9. Stack: ADT List
Implementation, Top
void showTop()
{
if ( isempty() )
cout<<"Stack is Empty";
else
cout<<"Element at top is : "<< top->data;
}
10. Stack: ADT List
Implementation, Display
void displayStack()
{
if ( isempty() )
cout<<"Stack is Empty";
else
{
Node *temp=top;
while(temp!=NULL)
{ cout<<temp->data<<" ";
temp=temp->next; }}}
11. Simple Applications of the ADT Stack:
Checking for Balanced Braces
A stack can be used to verify whether a program
contains balanced braces
An example of balanced braces
abc{defg{ijk}{l{mn}}op}qr
An example of unbalanced braces
abc{def}}{ghij{kl}m
abc{def}{ghij{kl}m
12. Checking for Balanced Braces
Requirements for balanced braces
Each time you encounter a “}”, it matches an already
encountered “{”
When you reach the end of the string, you have matched
each “{”
13. Checking for Balanced Braces
Traces of the algorithm that checks for balanced braces
14. Evaluating Postfix
Expressions
A postfix (reverse Polish logic) calculator
Requires you to enter postfix expressions
Example: 2 3 4 + *
When an operand is entered, the calculator
Pushes it onto a stack
When an operator is entered, the calculator
Applies it to the top two operands of the stack
Pops the operands from the stack
Pushes the result of the operation on the stack