DATA STRUCTURES AND ALGORITHM��STACK
Week 2
Instructor: Dr. Usman Ashraf
Email: usman.ashraf@gcwus.edu.pk
04th Sep, 2018
Stacks
2
Insertion and deletion on stack
3
Operation On Stack
4
Push and Pop
5
Stack-Related Terms
6
Stack Implementation
7
Static Implementation
8
Static Implementation
9
1
2
3
Static Implementation
Since, in a stack the insertion and deletion take place only at the top, so…
10
A better Implementation:
Static Implementation: A better Implementation
11
A
40
35
1
2
3
4
45
30
|
|
|
|
|
|
maxlength
top
45
40
35
30
A Simple Stack Class
class IntStack{
private:
int *stackArray;
int stackSize;
int top;
public:
IntStack(int);
bool isEmpty();
bool isFull();
void push();
void pop();
void displayStack();
void displayTopElement();
};
12
Constructor
IntStack::IntStack(int size)
{
stackArray = new int[size];
stackSize = size;
top = -1;
}
13
Push( )
void IntStack::push()
{
clrscr();
int num;
if(top>=stackSize)
cout<<"stack Overflow"<<endl;
else
{
cout<<"Enter Number=";
cin>>num;
top++;
stackArray[top]=num;
}
}
14
Pop( )
void IntStack::pop()
{
clrscr();
if(top == -1)
cout<<"Stack Underflow"<<endl;
else
{
cout<<"Number Deleted From the stack=";
cout<<stackArray[top];
top--;
}
getche();
}
15
Main( )
void main ()
{
IntStack stack(5);
int choice;
do
{
cout<<“Menu"<<endl;
cout<<"1-- PUSH"<<endl;
cout<<"2-- POP"<<endl;
cout<<"3– DISPLAY "<<endl;
cout<<"4-- Exit"<<endl;
cout<<"Enter choice=";
cin>>choice;
switch(choice)
{
case 1:
stack.push(); break;
case 2:
stack.pop(); break;
case 3:
stack.displayStack();
break;
}
}while(choice!=4);
getche();
}
16
Dynamic Implementation of Stacks
17
NULL
x
y
z
Top
Dynamic Implementation of Stack
Class Definition
18
class Node{ int data; Node *next; public: void setData(int); int getData(); void setNext(Node*); Node* getNext(); }; | class ListStack{ private: Node* top; public: ListStack(){ top=NULL;} void push(); void pop(); void display(); }; |
Push( ) Function
void ListStack::push()
{
Node *newNode;
newNode= new Node;
cout<<“Enter number to add on stack";
cin>> (newNode->setData(num));
newNode->setNext(top);
top=newNode;
}
19
10
20
top
Pop( ) Function
void ListStack::pop()
{
Node *temp;
temp=top;
if(top==NULL)
cout<<"Stack UnderFlow"<<endl;
else
{
cout<<"deleted Number from the stack =";
cout<<top->getData();
top=top->getNext();
delete temp;
}
}
20
Main( ) Function
void main()
{
clrscr();
ListStack LS;
int choice;
do{
cout<<"Menu "<<endl;
cout<<"1.Push" <<endl;
cout<<"2.Pop"<<endl;
cout<<"3.Show"<<endl;
cout<<"4.EXIT"<<endl;
cin>>choice;
switch(choice){
case 1:
LS.push();
break;
case 2:
LS.pop();
break;
case 3: LS.display();
break;
}
}while(choice!=4);
}
21
Stack applications
22
C++ Run-time Stack
23