Chapter 3
Chapter 3
Computer Engg.
Unit -3
Stacks and Queues
Prepared By
Mrs. Kavita G Kurale
What is a Stack?
In a stack,
1. the insertion operation is performed using a function called "push“
2. deletion operation is performed using a function called "pop".
• A stack data structure can be defined as follows...
• 1. Using Array
• A stack data structure can be implemented using a one-dimensional array. But
stack implemented using array stores only a fixed number of data values. This
implementation is very simple. Just define a one dimensional array of specific size
and insert or delete the values into that array by using LIFO principle with the help
of a variable called 'top'.
• Initially, the top is set to -1. Whenever we want to insert a value into the stack,
increment the top value by one and then insert. Whenever we want to delete a
value from the stack, then delete the top value and decrement the top value by
one.
• Stack Operations using Array
• Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' with specific value.
• Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
• Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
• Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the
stack.
• Stack Operations using Array
• Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' with specific value.
• Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' with specific value.
• Step 3 - If it is NOT FULL, then increment top value by one (top++) and set
stack[top] to value (stack[top] = value).
• pop() - Delete a value from the Stack
void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
• void push(int value){
• if(top == SIZE-1)
• printf("\nStack is Full!!! Insertion is not possible!!!");
• else{
• top++;
• stack[top] = value;
• printf("\nInsertion success!!!");
• }
• }
• void pop(){
• if(top == -1)
• printf("\nStack is Empty!!! Deletion is not possible!!!");
• else{
• printf("\nDeleted : %d", stack[top]);
• top--;
• }
• }
• void display(){
• if(top == -1)
• printf("\nStack is Empty!!!");
• else{
• int i;
• printf("\nStack elements are:\n");
• for(i=top; i>=0; i--)
• printf("%d\n",stack[i]);
• }
• }
Applications of Stack