Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
111 views

Lecture 6 Stack DataStructure in C++

The document discusses stacks and their implementation using arrays and linked lists in C++. It begins by defining what a stack is - a LIFO data structure where elements can only be inserted or removed from one end called the top. It then provides examples of stack operations like push, pop and discusses implementing stacks using arrays and linked lists. For arrays, it shows the push and pop algorithms and provides a sample code. For linked lists, it explains how to implement push and pop by adding/removing nodes from the head of the list.

Uploaded by

Simple lyrics
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
111 views

Lecture 6 Stack DataStructure in C++

The document discusses stacks and their implementation using arrays and linked lists in C++. It begins by defining what a stack is - a LIFO data structure where elements can only be inserted or removed from one end called the top. It then provides examples of stack operations like push, pop and discusses implementing stacks using arrays and linked lists. For arrays, it shows the push and pop algorithms and provides a sample code. For linked lists, it explains how to implement push and pop by adding/removing nodes from the head of the list.

Uploaded by

Simple lyrics
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Stack DataStructure in C++

Introduction to Stacks
• The stack is one of the most important data structures in computer
science. To understand how a stack works, think of a deck of playing
cards that is face down. We can only easily access the card that is on top.
When we want to look at the top card, there are two things we can do:
we can peek at it, but leave it on the stack, or we can pop it off. When we
pop off the top object, we are taking it off the stack. If we want to add
another card to the top of the stack, we push.

• A stack is called a last-in-first-out (LIFO) collection. This means that the


last thing we added (pushed) is the first thing that gets pulled (popped)
off. If the last card we put on our stack of cards was an ace, then the first
card we pulled from the top is that same ace.
What is a Stack
• A stack is an ordered list in which all insertions and deletions are made at
one end, called the top
• Adding an element is called as pushing the element onto the stack. The
function, which does this, is called ‘push’.
• Removing an element from the stack is called as popping the element
from the stack and the function, which does this, is called ‘pop’
• A stack is a last in, first out (LIFO) data structure i.e. Items are removed
from a stack in the reverse order from the way they were inserted
• These two operations (pop and push) implements the LIFO method .
• A stack is a sequence of items that are ACCESSIBLE AT ONLY ONE END of
the sequence
Examples of Stacks
Stacks
• Stacks are considered to be the easiest type of list to use.

• The only operations we have on stacks are to add things to


the top of the stack and to remove things from the top of
the stack.

• We never need to insert, delete, or access data that is


somewhere other than at the top of the stack.
Stack Operations

1. PUSH : It is used to insert items into the stack.


push(e) -> inserts element e into the stack

2. POP: It is used to delete items from stack.


pop( ) ->deletes & returns the last inserted element in the stack

3. size( ) return the number of elements in the stack

4. isEmpty( ) return true if stack is empty and false if stack is not empty

TOP: It represents the current location of data in stack.


Stack Operations(2)
Stack Operations(3)

• There are two stack errors that


can occur:
• UNDERFLOW: trying to pop
an empty stack

• OVERFLOW: trying to push


onto an already full stack
Algorithm of insertion in
Stack: (push)
1. Insertion(a, top, item, max)
2. If top=max then
print ‘STACK OVERFLOW’
exit
else
3. top=top+1
end if
4. a[top]=item
5. Exit
Algorithm of deletion in
stack: (pop)

1.Deletion(a, top, item)


2. If top=0 then
print ‘STACK UNDERFLOW’
exit
else
3. item=a[top]
end if
4. top=top-1
5. Exit
Algorithm of display in
stack:
1.Display(top, i, a[i])
2.If top=0 then
Print ‘STACK EMPTY’
Exit
Else
3.For i=top to 0
Print a[i]
End for
4.exit
Stack Implementations
• Stack can be implemented using arrays or using linked lists.
• To implement a stack, items are inserted and removed at the SAME END (called the top)
(1) Array Implementation of a stack
• For array implementation its size should be predefined and also it cannot exceed run
time

• To use an array to implement a stack, you need both the array itself and an integer.
The integer tells you either:
• Which location is currently the top of the stack, or
• How many elements are in the stack

• Each element of the stack is assigned an array slot

• To keep track of the top position, declare a variable called top

• The top of the stack is the index of the last element added to the stack
Array Implementation of a stack
The Push Operation

• Initially when the stack is empty, TOP can have any integer value OTHER THAN any
valid index number of the array. Let top = -1;

• The first element in the empty stack goes to the 0th position of the array and the
top is initialized to value 0.

• After this, every push operation increments the top variable by 1 and inserts new
data at that particular position.

• As arrays are fixed in length, elements CAN NOT be inserted beyond the maximum
size of the array.

• Pushing data beyond the maximum size of the stack results in “data overflow”.
Array Implementation of a stack
The Push Operation (2)
Array Implementation of a stack
The Pop Operation
• The pop operation deletes the most recently entered item from the
stack.

• Any attempt to delete an element from the empty stack results in


“data underflow” condition.

• The variable top contains the index number of the current top position
of the stack.

• Each time the pop operation is performed, the top variable is


decremented by 1.
Array Implementation of a stack
The Pop Operation(2)
Array Implementation of a Stack| Code

#include<iostream>
using namespace std;

int stack[100],choice,n,top,x,i;
void push(void); //function declarations
void pop(void);
void display(void);
Array Implementation of a Stack| Code (cont..)
int main(){ //main menu
top=-1;
cout<<"\n Enter the size of STACK[MAX=100]:";
cin>>n;
cout<<"\n\t STACK OPERATIONS USING ARRAY"<<endl;
cout<<"\n\t--------------------------------";
cout<<"\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT";
cout<<"\n\t--------------------------------";
do{
cout<<"\n Enter the Choice:";
cin>>choice;
Array Implementation of a Stack| Code (cont..)

switch(choice) {
case 1:push(); break;
case 2:pop();break;
case 3:display();break;
case 4:cout<<"\n\t EXIT POINT ";break;
default:cout<<"\n\t Please Enter a Valid Choice(1/2/3/4)";
}
}
while(choice!=4);
return 0;
}
Array Implementation of a Stack| Code (cont..)
void push(){ //push function
if(top>=n-1){
cout<<"\n\tSTACK is over flow"<<endl;
}
else {
cout<<" Enter a value to be pushed: ";
cin>>x;
top++;
stack[top]=x;
}
}
Array Implementation of a Stack| Code (cont..)
void pop(){ //pop function
if(top<=-1){
cout<<"\n\t Stack is under flow"<<endl;
}
else{
cout<<"\n The popped elements is "<<stack[top]<<endl;
top--;
}
}
Array Implementation of a Stack| Code (cont..)
void display(){ //display function
if(top>=0){
cout<<"\n The elements in STACK \n";
for(i=top; i>=0; i--)
cout<<stack[i]<<endl;
cout<<"\n Press Next Choice"<<endl;
}
else{
cout<<"\n The STACK is empty"<<endl;
}
}
Array Implementation of a Stack| Output
(2) Linked List Implementation of a Stack
• Each node of a stack as a linked list has two parts : data part and link
part and is created with the help of self referential structure (node
*next;)
• . The data part stores the data and link part stores the address of the
next node of the linked list.
Linked List Implementation of a Stack
• NB: The top is at the HEAD AND NOT AT THE TAIL of a linked list.
Can you imagine what would happen if top was at the tail? What
would be the implication of push and pop operations? Push
would be fine if a tail pointer were provided...but Pop would be
disastrous, requiring traversal!! But because the top is at the
“head”, push and pop are essentially “direct access”, no
traversals needed!
• In implementing Stack as a linked list the top of the stack is
represented by the first item in the linked list. To implement
push: create a new node and attach it as the new first node. To
implement pop: advance the top of stack to the second item in
the list (if there is one).
Linked List Implementation of a Stack
The Push Operation
Linked List
Implementation of a Stack
The Pop Operation
Linked List Implementation of a Stack
#include<iostream> • Recall that Self Referential
Structures: are special
using namespace std; structures which contains
pointers to themselves (node
*next;).
struct node{
int reg_num;
• Here, next is a pointer of type
char name[20]; node itself.
float mark;
}; • Self Referential structures are
needed to create Linked Lists.
Linked List Implementation of a Stack (cont..)
class stack{ • class stack: It contains pointer TOP
which will point to the top of the
node *top; stack.
public :
stack(){ • A Constructor (stack())has same
top=NULL;} name as the class itself. 
A constructor is automatically called
void push(); when an object is created
void pop();
void display(); • The constructor function initializes
TOP to NULL.
};
Linked List Implementation of a Stack (cont..)
void stack::push(){ • Scope resolution operator (::) in C++ is used to define a
function outside a class
node *temp;
temp=new node; • node *temp; // pointer of type node
cout<<"Enter reg_num : ";
cin>>temp->reg_num; • new operator will create a new node and address of new
node is stored in temp
cout<<"\n Enter name : ";
cin>>temp->name; • temp->next=top;
cout<<"\n Enter mark : "; // address stored in TOP gets stored in next of newly created
node.
cin>>temp->mark;
temp->next=top; • top=temp;
top=temp; // Top will contain address of newly created node
}
Linked List Implementation of a Stack (cont..)
void stack::pop(){
• if(top!=NULL) // if stack is not empty
if(top!=NULL){
node *temp=top;
• node *temp=top; // temp is a pointer
top=top->next; containing address of first node
cout<<temp->reg_num<<temp-
>name<<temp->mark
• top=top->next; // top will now contain address
<<"deleted"; of second node
delete temp;
} • delete temp; // delete operator will delete the
else node stored at temp
cout<<"Stack empty";
}
do{
cout<<endl<<"------------------"<<endl;
cout<<"\nSTACK OPTION \nP PUSH \n
void stack::display(){ O POP \nD DISPLAY \nQ QUIT\n";
cout<<endl<<"------------------"<<endl;
node *temp=top;
cin>>ch;
while(temp!=NULL){
switch(ch){
cout<<temp->reg_num<<temp>name<<temp->mark<<" ";
case 'P':
temp=temp->next;
st.push();break;
} case 'O':
} st.pop();break;
case 'D':
st.display();break;
int main(){ }
stack st; }while(ch!='Q');
char ch;
return 0;}
Arrays vs Linked-List Implementations
Array Implementation Linked List Implementation

Ease of simple and efficient Not so easy to implement


implementation

The size of array must be Size of a Linked List is variable.


Size specified at time of array It grows at runtime, as more
declaration/initialization.   nodes are added to it. 

Memory Memory utilization is inefficient memory utilization is efficient


Utilization in the array.   in the linked list.  

Memory is allocated as soon as Memory is allocated at runtime


Memory the array is declared, at compile as and when a new node is
Allocation time. This is referred to as static added. It’s also known as
memory allocation.   Dynamic Memory Allocation.
When to use the stack data structure?
• A stack is an appropriate data structure to use when
information needs to be stored and then later retrieved in
reverse order

• So, which data structure is best for a stack? If we know how


large the stack should be and are sure that the size won’t
change or vary during implementations then use arrays
however If the size varies greatly, or cannot be allocated
contiguously, or is unknown then use linked lists
Application of Stacks
1. Function Call: In computer programming processing of function calls and
their terminations uses stack. Stack is used to remember the place where
the call was made; so that it can return there after the function is
complete
2. Internet Web browsers store the addresses of recently visited sites on a
stack. Each time one visits a new site ==> pushed on the stack. Browsers
allow to “pop” back to previously visited site.
3. The undo-mechanism in an editor. The changes are kept in a stack. When
the user presses “undo” the stack of changes is popped.
4. Backtracking: Suppose we are finding a path for solving maze problem.
We choose a path and after following it we realize that it is wrong. Now
we need to go back to the beginning of the path to start with new path.
This can be done with the help of stack. NB Backtracking algorithms (are
often used in optimizations and in games)
7. Syntax Parsing: Many compilers use
Application of Stacks(2) a stack for parsing the syntax of
expressions, program blocks etc.
before translating into low level
5. Expression Evaluation: Stack code.
is used to evaluate prefix,
postfix and infix expressions.
8. Parenthesis Checking: Stack is used
to check the proper opening and
6. Expression Conversion: An closing of parenthesis.
expression can be represented
in prefix, postfix or infix
notation. Stack can be used to 9. String Reversal: Stack is used to
convert one form of reverse a string. We push the
expression to another. characters of string one by one into
stack and then pop character from
stack.
Application of Stacks: (8)Parenthesis Checking
• Stacks are also used to check
whether a given arithmetic
expressions containing nested
parenthesis is properly
parenthesized.
• The program for checking the
validity of an expression verifies
that for each left parenthesis
braces or bracket ,there is a
corresponding closing symbol and
symbols are appropriately nested.
Application of Stacks
(9) String Reversal …. • For example: To reverse the
string ‘REVERSE’ the string is
read from left to right and its
• A simple application of stack is characters are pushed . LIKE
reversing strings. To reverse a string
, the characters of string are pushed
onto the stack one by one as the
string is read from left to right.
• Once all the characters of string are
pushed onto stack, they are popped
one by one. Since the character last
pushed in comes out first,
subsequent pop operation results in
the reversal of the string
Check the Following YouTube Videos
• https://
www.youtube.com/watch?v=F1F2imiOJfk&list=PL2_aWCzGMAwI3
W_JlcBbtYTwiQSsOTa6P&index=14&frags=pl%2Cwn

• https://
www.youtube.com/watch?v=sFVxsglODoo&list=PL2_aWCzGMAwI3
W_JlcBbtYTwiQSsOTa6P&index=15

• https://www.youtube.com/watch?v=MuwxQ2IB8lQ&list=PL2_aWCz
GMAwI3W_JlcBbtYTwiQSsOTa6P&index=16

You might also like