You are on page 1of 17

Chapter 3- Stack

Stack 3

3.1 What is a stack?


3.2 Operations on Stack
3.3 Array based implementation of stack
3.4 Linked list implementation of stack
3.5 Applications of Stack
3.6 Summary
3.7 Key Terms
3.8 Review Questions

32
Chapter 3- Stack

Objectives
To understand the concept of stack
To learn how to implement the stack
To understand the various applications of stack

3.1 What is a stack?

A tree can be defined in several ways. One natural way to define a tree is recursively. A
tree is a collection of nodes. The collection can be empty, which is sometimes denoted as A.
Otherwise, a tree consists of a distinguished node r, called the root, and zero or more (sub) trees
T1, T2, . . . ,Tk, each of whose roots are connected by a directed edge to r. The root of each
subtree is said to be a child of r, and r is the parent of each subtree root.

A stack is a linear structure in which item may be added or removed only at one end.
There are certain frequent situations in computer science when one wants to restrict
insertions and deletions so that they can take place only at the beginning or the end of the end of
the list, not in the middle. Two of the Data Structures that are useful in such situations are Stacks
and queues. A stack is a list of elements in which elements may be inserted or deleted only at one
end, called the Top. This means, in particular, the elements are removed from a stack in the
reverse order of that which they are inserted in to the stack. The stack also called "last-in first -
out (LIFO)” list.

Top
3
2

6
Figure 3.1 - Stack

33
Chapter 3- Stack

3.2 Operations on Stack


Special terminology is used for two basic operations associated with stack:
1. "Push" is the term used to insert an element into a stack.
2. "Pop" is the term used to delete an element from a stack.

Example
1. Practical daily life: A pile of heavy books kept in a vertical box, dishes kept one on
top of another.

3.3 Array based implementation of stack

Stack data structure can be implemented using arrays. All the insertion (push) and deletion
operation (pop) can be performed in LIFO (Last In First Out) manner. Here, the elements can be
inserted up to the size of the array. The operations can be performed under stack is push(), pop()
and top ( ).

Operations
 Push
 Pop
 Top

(i) Push
This is used to push an element into the stack using an array. Whenever the stack is full, we
cannot insert any item into the stack. Otherwise, we push an item by increment the top pointer by
1 and assign the item into the top position.

Algorithm

Push(item, array , n, top)


{
if ( n> = top) Then
print "Stack is full" ;
else
{
top = top + 1;
array[top] = item ;
}
} } }

34
Chapter 3- Stack

Example

1. Initially, we have an empty stack. Insert an item 11 into the stack.

Figure 3.2 – Push an item 11 into the stack

2. Insert 23 into the stack. Move the top pointer one step ahead and assign an item into the top
position.

35
Chapter 3- Stack

3. Similarly, insert the elements -8, 16, 27, 14, 20 into the stack. Now the stack is FULL, since it
has 7 elements.

(ii) Pop
This is used to delete or pop an element from the stack. Initially check whether the stack
is empty or not. If it is empty then return FALSE. Otherwise decrement the top pointer by 1.
Then the last inserted item will be deleted automatically.

Example
1. Pop an from from the stack. Stack contains 11, 23, -8, 16, 27, 14 and 20. From this, the last
inserted tiem 20 will be deleted and the top pointer will be decremented.

Figure 3.3 – Pop an item from the stack

36
Chapter 3- Stack

Algorithm

Pop(item, array, top)


{
if ( top<= 0) Then
print " stack is empty".
else
{
item = array[top];
top = top - 1;
}
}

(iii) Top
This is used to return the last inserted item. First we check whether the stack is empty or not. If
the stack is empty then return NULL. Otherwise it returns the last inserted item i.e., the top
element.

Algorithm

Top(array)
{
if(top<=0)
print “stack is empty”
else
return array[top];
}

3.4 Linked list implementation of stack


Stack data structure can be implemented using linked list. All the insertion(push) and deletion
operation(pop) can be performed in LIFO(Last In First Out) manner. Here, the elements can be
inserted up to the size of storage space. The operations can be performed under stack is push(),
pop() and top().

(i) push()
This is the function which is for insertion(pushing)of an element into stack. It is similar to the
insertion of an element at the beginning of a single linked list. The steps to be followed,

37
Chapter 3- Stack

o Get the element to be inserted


o Create a new cell to store the new element using malloc()
o If the linked list is empty, then insert the new element as the first cell of the linked
list and assign the address the new cell to NULL
o Otherwise, insert the new cell in the first of linked list by rearranging the pointers

Figure 3.4 – Push Operation(Linked List implementation of stack)


Algorithm

void push( element_type x, STACK S )


{
node_ptr tmp_cell;
tmp_cell = (node_ptr) malloc( sizeof ( struct node ) );
tmp_cell->element = x;
tmp_cell->next = S->next;
S->next = tmp_cell;
}

(ii) pop()
This is the function which is for deletion (popping up) of an element from the stack. It is
similar to the deletion of an element at the beginning of a single linked list. Before deleting the
element, check whether the stack(linked list) is empty or not. If it is empty then return error
otherwise delete the first element from the linked list by rearranging the pointer.

top 5 9 12

Figure 3.5 – Pop Operation(Linked List implementation of stack)

38
Chapter 3- Stack

Algorithm

void pop( STACK S )


{
node_ptr first_cell;
if( is_empty( S ) )
error("Empty stack");
else
{
first_cell = S->next;
S->next = S->next->next;
free( first_cell );
}
}

(iii) top()
This function is used to return he top element in the stack which means that the last inserted
element.

Algorithm

element_type top( STACK S )


{
if( is_empty( S ) )
error("Empty stack");
else
return S->next->element;
}

3.4.1 C program for linked list implementation of stack


/* C Program for linked list implementation of stack*/
# include <stdio.h>
# include <stdlib.h>
# include <conio.h>
# define NULL 0

39
Chapter 3- Stack

struct stack
{
int data;
struct stack *next;
};
typedef struct stack node;
node *top = NULL;
void main()
{
int choice;
void push();
void pop();
void display();
clrscr();
while(1)
{
printf(“\t\t\t Stack \n\n\n”);
printf(“\t 1. Push \n”);
printf(“\t 2. Pop \n”);
printf(“\t 3. Display \n”);
printf(“\t 4. Exit \n”);
printf(“\t Enter Your Choice:\n”);
scanf(“%d”,&choice);
switch (choice)
{
case 1 : push();
break;
case 2 : pop();
break;
case 3 : display();
break;
case 4: exit(0);
}/* switch end*/
} /*while end*/
}/*main end*/

// creation of stack - insertion


void push()
{

40
Chapter 3- Stack

node *newnode, *temp;


newnode = (node *)malloc(sizeof(node));
printf(“Enter the data field :”);
scanf(“%d”,&newnode->data);
newnode->next = NULL;
if(top == NULL)
top= newnode;
else
{
newnode->next = top;
top = newnode;
}
return;
}

/* Function to delete an element - pop*/


void pop()
{
node *temp;
int item;
if(top == NULL)
printf(“Stack underflow”);
else
{
item = top->data;
temp = top;
top = top->next;
free(temp);
printf(“deleted data :%d”, item);
} / *else end*/
return;
}

/* Function to display the elements */


void display()
{
node *temp;
temp =top;
while(temp != NULL)

41
Chapter 3- Stack

{
printf(“%d---------- >”, temp->data);
temp = temp->next;
}
return;
}

3.5 Applications of Stack

1. Balancing symbols
2. Evaluating postfix expression
3. Conversion from infix to postfix form
4. Recursive function call

3.5.1 Balancing symbols


This is one of the applications of stack. Here, the stack is used to check whether the expression is
correctly balanced or not. The algorithm for balancing symbols is shown below.
Algorithm

Step 1: Read symbols in the expression one by one and do steps 2-3 till the
end of the expression.
Step 2: If symbol is opening parenthesis then
Push the symbol onto a stack
Step 3: If symbol is closing parenthesis then
Pop the top element (corresponding open parenthesis) from the stack
If pop returns Null (i.e. stack empty) then
Print “Excess closing parenthesis”
Return
Step 4: If stack is not empty then
Print “Excess opening parenthesis”
Else
Print “ Parenthesis balanced”
Step 5: End

3.5.2 Evaluating postfix expression


The stack is used to evaluate the postfix expression. To implement this, we use the push and pop
operation of stack.

42
Chapter 3- Stack

Algorithm

Step 1: Read the characters of postfix expression one by one and do steps 2-3 till
the end of the expression.
Step 2: If the current character is an operand then
Push it onto Stack.
Step 3: If the current character is an operator then
a. Pop an element and store as operand2.
b. Pop an element and store as operand1.
c. Evaluate the expression result = Operand1 Operator Operand2
d. Push result onto the Stack.
Step 4: End.

Example

Evaluate the postfix expression 6523+8*+3+* using stack.


1. Four operands 6, 5, 2 and 3 are pushed. 2. + is read; Pop 3, 2; Result = 3+2 =5; Push 5.

2 5

5 5

6 6

3. Push 8 4. * is read; Pop 8, 5; result = 8*5=40; Push 40

5 40

5 5

6 6

43
Chapter 3- Stack

5. + is read; Pop 40, 5; result = 40+5=45; 6. Push 3.

45 45

6 6

7. + is read; Pop 3, 45; result = 3+45=48; 8. * is read; Pop 48, 6; result = 48*6= 288;
Push 48 Push 288. This is the result of the postfix
expression

48

6 288

3.5.3 Conversion of infix to postfix form


Algorithm

Step 1: Read the infix string from left to right.


Step 2: Initialize an empty stack.
Step3: If the current character is an operand then
Add it to the Postfix string.
Step 4: If the current character is an operator and if the stack is empty then
Push the character onto stack.
Step 5: If the current character is an operator and the stack is not empty then
a. Compare the precedence of the character with the operator on
top of the stack (except “(“ )

44
Chapter 3- Stack

b. While operator at top of stack has high precedence over the current
Character and stack is not empty
(i) Pop the stack
(ii) Add the popped character to the postfix string
(iii) Push the operator onto the stack
Step 6: Repeat steps 3-5 till all the characters are read.
Step 7: While stack is not empty
a. Add operator in top of stack to postfix string.
b. Pop the stack.
Step 8: Return the postfix string.
Step 9: End

Example
Convert the Infix Expression: a + b * c + (d * e + f) * g into the postfix expression

1. Read a. It is a character. Write ‘a’ into 2. Read ‘*’. The precedence of ‘*’ is the
postfix. Read ‘+’. The stack is empty. greater than ‘+’. So, push ‘*’ into the
Push ‘+’ into the stack. Read ‘b’. Write ‘b’. Stack. Read ‘c’. Write ‘c’.

ab output abc

Postfix Postfix

*
+
+

Stack Stack

3. Read ‘+’. The precedence of ‘+’ is not greater 4. Read ‘(‘. Push it into the stack. Next
than the top element ‘*’ and the next element ‘+’. read ‘d’. Write it into the postfix.
So pop the element ‘*’ , ‘+’ and write it into the
postfix. Now push the input character ‘+’ into
the stack.

45
Chapter 3- Stack

abc*+ abc*+d

Postfix Postfix

+ +

Stack Stack

5. Read ‘*’. Push it to the stack. Next, read 6. Read ‘+’. The precedence of ‘+’ is
‘e’. Write ‘e’ into the postfix. smaller than the top element ‘*’. Pop ‘*’ and
write it into the postfix. Push ‘+’ into the
stack. Next, read ‘f’. Write it into the
postfix.

abc*+de abc*+de*f

Postfix Postfix
* +
( (
+ +

Stack Stack

7. Read ‘)’. Pop the operators from the stack 8. Read ‘*’. Push it into the stack. Read
upto ‘(‘. Stack contains only one character ‘+’ ‘g’. Write it into the postfix.
after ‘(‘. So, pop ‘+’ from stack and write it
into the postfix.

abc*+de*f+
abc*+de*f+g

Postfix Postfix

*
+
+

46
Chapter 3- Stack

9. Finally, the stack contains two operators ‘*’, ‘+’. Pop those operators and write it into the
postfix. Now the postfix expression is abc*+de*f+g*+

abc*+de*f+g*+

Postfix string

3.5.4 Function calls


Recursive function – Definition: A function which calls by itself repeatedly until the specified
condition is satisfied is called as recursive function.
Use of stack in function calls:
1. When there is a function call, all the important information such as variable
names, return address, arguments are to be saved using stack.
2. The information saved is called as stack frame.
3. Function call pushes stack frame into the stack whenever a function call is made.
4. When return statement is reached, the stack frame is popped out of the stack.
Example
Consider the code for the factorial program,
procedure Fact(int n)
{
if(n==1)
return 1;
else
return n * Fact(n-1);
}
The stack can push the function details whenever the function is called and pop the details of
function calls when the execution is finished.

Fig 3.6 - Function Calls & its Stack implementation

47
Chapter 3- Stack

For the above code, the stack can store the details of the factorial function is shown in figure 3.6.
Initially we start with n=5. Then call the factorial function recursively with 5*fact (4). The figure
shows the partial implementation of the factorial function.

3.6 Summary

Stack is a linear data structure. LIFO list. It has two operations namely push and pop. The
operations are done at top of the stack. It can be implemented using arrays and also in linked
list.

3.7 Key Terms

Stack, Push, Pop, recursive function and function call.

3.8 Review Questions ???????????

Two Mark Questions


1. Define stack.
2. What are the applications of stack?
3. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and Postfix
notations.
Big Questions
1. Explain the operations of stack using linked list.
2. Explain in detail about the applications of stack.
3. Explain the following implementation of stack ADT in detail.
i. Array implementation
ii. Linked list implementation
4. Convert the following infix expression into postfix form:
5. a). A + ( B – C * D ) / E * F * G – B
6. b) (A + B * C – ( D – C) / E / F ) – E
7. c) A + B * ( ( C + D ) / F ) + G * E
8. and evaluate the postfix expression for A=2, B=2, C=1,D=4, E=6, F=4, G=3
9. Explain the algorithm for the conversion from infix to postfix expression. Trace the
algorithm on the following input:
A+(B–C*D)/E*F*G–B

48

You might also like