You are on page 1of 32

DS – UNIT I

ARRAY AND STACK


I. ARRAY :

An array is a collection of items of the same variable type stored that are stored at contiguous
memory locations. It’s one of the most popular and simple data structures and is often used to
implement other data structures. Each item in an array is indexed starting with 0.

Array is a container which can hold a fix number of items and these items should be of the same
type. Most of the data structures make use of arrays to implement their algorithms. Following are
the important terms to understand the concept of Array.
 Element − Each item stored in an array is called an element.
 Index − Each location of an element in an array has a numerical index, which is used to
identify the element.

Array Representation

Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.

Arrays can be declared in various ways in different languages. For illustration, let's take C array
declaration.

As per the above illustration, following are the important points to be considered.
 Index starts with 0.
 Array length is 10 which means it can store 10 elements.
 Each element can be accessed via its index. For example, we can fetch an element at index
6 as 9.
Basic Operations

Following are the basic operations supported by an array.


 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or by the value.
 Update − Updates an element at the given index.
II. STRINGS :

Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’.
Below are some examples of strings:
“geeks”, “for”, “geeks”, “GeeksforGeeks”, “Geeks for Geeks”, “123Geeks”, “@123 Geeks”

How String is represented in Memory?

In C, a string can be referred to either using a character pointer or as a character array. When
strings are declared as character arrays, they are stored like other types of arrays in C. For example,
if str[] is an auto variable then the string is stored in the stack segment, if it’s a global or static
variable then stored in the data segment, etc.
III. STACK :
IV. OPERATION ON STACK:

The stack data structure is a linear data structure that accompanies a principle known as LIFO
(Last In First Out) or FILO (First In Last Out). Real-life examples of a stack are a deck of cards,
piles of books, piles of money, and many more.

A stack is an abstract data type that holds an ordered, linear sequence of items. In contrast
to a queue, a stack is a last in, first out (LIFO) structure. A real-life example is a stack of plates:
you can only take a plate from the top of the stack, and you can only add a plate to the top of the
stack.
Examples of stacks in "real life": The stack of trays in a cafeteria; A stack of plates in a
cupboard; A driveway that is only one car wide.
A Stack can be used for evaluating expressions consisting of operands and operators. Stacks
can be used for Backtracking, i.e., to check parenthesis matching in an expression. It can also be
used to convert one form of expression to another form. It can be used for systematic Memory
Management.
A pile of books, a stack of dinner plates, a box of pringles potato chips can all be thought of
examples of stacks. The basic operating principle is that last item you put in is first item you can
take out.

A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has
one end, whereas the Queue has two ends (front and rear). It contains only one pointer top
pointer pointing to the topmost element of the stack. Whenever an element is added in the stack,
it is added on the top of the stack, and the element can be deleted only from the stack. In other
words, a stack can be defined as a container in which insertion and deletion can be done from
the one end known as the top of the stack.

Some key points related to stack


o It is called as stack because it behaves like a real-world stack, piles of books, etc.
o A Stack is an abstract data type with a pre-defined capacity, which means that it can store
the elements of a limited size.
o It is a data structure that follows some order to insert and delete the elements, and that
order can be LIFO or FILO.
Working of Stack

Stack works on the LIFO pattern. As we can observe in the below figure there are five memory
blocks in the stack; therefore, the size of the stack is 5.

Suppose we want to store the elements in a stack and let's assume that stack is empty. We have
taken the stack of size 5 as shown below in which we are pushing the elements one by one until
the stack becomes full.

Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it goes
from the top to the bottom when we were entering the new element in the stack. The stack gets
filled up from the bottom to the top.

When we perform the delete operation on the stack, there is only one way for entry and exit as
the other end is closed. It follows the LIFO pattern, which means that the value entered first will
be removed last. In the above case, the value 5 is entered first, so it will be removed only after
the deletion of all the other elements.

Standard Stack Operations

The following are some common operations implemented on the stack:

o push(): When we insert an element in a stack then the operation is known as a push. If
the stack is full then the overflow condition occurs.
o pop(): When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an
underflow state.
o isEmpty(): It determines whether the stack is empty or not.
o isFull(): It determines whether the stack is full or not.'
o peek(): It returns the element at the given position.
o count(): It returns the total number of elements available in a stack.
o change(): It changes the element at the given position.
o display(): It prints all the elements available in the stack.

PUSH operation

The steps involved in the PUSH operation is given below:

o Before inserting an element in a stack, we check whether the stack is full.


o If we try to insert the element in a stack, and the stack is full, then the overflow condition
occurs.
o When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
o When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
o The elements will be inserted until we reach the max size of the stack.

POP operation

The steps involved in the POP operation is given below:

o Before deleting the element from the stack, we check whether the stack is empty.
o If we try to delete the element from the empty stack, then the underflow condition
occurs.
o If the stack is not empty, we first access the element which is pointed by the top
o Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
A stack is an Abstract Data Type (ADT), commonly used in most programming languages.
It is named stack as it behaves like a real-world stack, for example – a deck of cards or a pile of
plates, etc. A real-world stack allows operations at one end only.
V. REPRESENTATION OF STACK USING ARRAY & LINKED LIST :

In our day to day life, we see stacks of plates, coins, etc. All these stacks have one thing in
common that a new item is added at the top of the stack and any item is also removed from the
top i.e., the most recently added item is removed first.

In Computer Science also, a stack is a data structure which follows the same kind of rules i.e.,
the most recently added item is removed first. It works on LIFO (Last In First Out) policy. It
means that the item which enters at last is removed first.

Since a stack just has to follow the LIFO policy, we can implement it using a linked list as well
as with an array. However, we will restrict the linked list or the array being used to make the
stack so that any element can be added at the top or can also be removed from the top only.

A stack supports few basic operations and we need to implement all these operations (either with
a linked list or an array) to make a stack.

These operations are:

Push → The push operation adds a new element to the stack. As stated above, any element
added to the stack goes at the top, so push adds an element at the top of a stack

Pop → The pop operation removes and also returns the top-most (or most recent element) from
the stack.

Top → The Top operations only returns (doesn’t remove) the top-most element of a stack.

isEmpty → This operation checks whether a stack is empty or not i.e., if there is any element
present in the stack or not.

We also handle two errors with a stack. They are stack underflow and stack overflow. When
we try to pop an element from an empty stack, it is said that the stack underflowed. However, if
the number of elements exceeds the stated size of a stack, the stack is said to be overflowed.
At many places, you might find out that a stack is referred to as an abstract data type which
creates confusion in our mind about whether a stack is an abstract data type or a data structure?
So, let’s discuss.

Stack – [Abstract Data Type or Data Structure]:

In an Abstract Data Type (or ADT), there is a set of rules or description of the operations that
are allowed on data. It is based on a user point of view i.e., how a user is interacting with the
data. However, we can choose to implement those set of rules differently.

A stack is definitely an ADT because it works on LIFO policy which provides operations like
push, pop, etc. for the users to interact with the data. A stack can be implemented in different
ways and these implementations are hidden from the user. For example, as stated above, we can
implement a stack using a linked list or an array. In both the implementations, a user will be able
to use the operations like push, pop, etc. without knowing the data structure used to implement
those operations.

However, when we choose to implement a stack in a particular way, it organizes our data for
efficient management and retrieval. So, it can be seen as a data structure also.
Till now, we know about stacks and operations involved with a stack.

Applications of Stack :

There are many applications of a stack. Some of them are:

 Stacks are used in backtracking algorithms.


 They are also used to implement undo/redo functionality in a software.
 Stacks are also used in syntax parsing for many compilers.
 Stacks are also used to check proper opening and closing of parenthesis.
Stack Using Array:

We are going to use the element at the index 1 of the array as the bottom of the stack and the last
element of the stack as the top of the stack as described in the picture given below.

Since we need to add and remove elements from the top of the stack, we are going to use a
pointer which is always going to point the topmost element of the stack. It will point to the
element at index 0 when the stack is empty.

So, let’s first write a function to check whether a stack is empty or not.
IS_EMPTY(S)
if S.top == 0
return TRUE
return FALSE
We are going to consider only the elements from 1 to S.top as part of the stack. It might be
possible that there are other elements also in the array but we are not going to consider them as
stack.

To add an item to a stack (push), we just need to increment the top pointer by 1 and add the
element there.
PUSH(S, x) → Here, S is the stack and x is the item we are going to push to the stack.
Let’s suppose that S.size is the maximum size of the stack. So, if S.top+1 exceeds S.size, then
the stack is overflowed. So, we will first check for the overflowing of the stack and then
accordingly add the element to it.

PUSH(S, x)
S.top = S.top+1
if S.top > S.size
Error "Stack Overflow"
else
S[S.top] = x
Similarly to remove an item from a stack (pop), we will first check if the stack is empty or not. If
it is empty, then we will throw an error of "Stack Underflow", otherwise remove the element
from the stack and return it. 

POP(S)
if IS_EMPTY(S)
Error “Stack Underflow”
else
S.top = S.top-1
return S[S.top+1]

PROGRAM :

#include <stdio.h>

#define SIZE 10

int S[SIZE+1];
int top = 0;

int is_empty() {
if(top == 0)
return 1;
return 0;
}

void push(int x) {
top = top+1;
if(top > SIZE) {
printf("Stack Overflow\n");
}
else {
S[top] = x;
}
}

int pop() {
if(is_empty()) {
printf("Stack Underflow\n");
return -1000;
}
else {
top = top-1;
return S[top+1];
}
}

int main() {
pop();
push(10);
push(20);
push(30);
push(40);
push(50);
push(60);
push(70);
push(80);
push(90);
push(100);
push(110);

int i;
for(i=1; i<=SIZE; i++) {
printf("%d\n",S[i]);
}
return 0;
}
Stack Using Linked List:

A stack using a linked list is just a simple linked list with just restrictions that any element will
be added and removed using push and pop respectively. In addition to that, we also
keep top pointer to represent the top of the stack. This is described in the picture given below.

A stack will be empty if the linked list won’t have any node i.e., when the top pointer of the
linked list will be null. So, let’s start by making a function to check whether a stack is empty or
not.
IS_EMPTY(S)
if S.top == null
return TRUE
return FALSE

Now, to push any node to the stack (S) - PUSH(S, n), we will first check if the stack is empty or
not. If the stack is empty, we will make the new node head of the linked list and also point
the top pointer to it.

PUSH(S, n)
if IS_EMPTY(S) //stack is empty
S.head = n //new node is the head of the linked list
S.top = n //new node is the also the top

If the stack is not empty, we will add the new node at the last of the stack. For that, we will
point next of the top to the new node - (S.top.next = n) and the make the new node top of the
stack - (S.top = n).

PUSH(S, n)
if IS_EMPTY(S) //stack is empty
...
else
S.top.next = n
S.top = n
PUSH(S, n)
if IS_EMPTY(S) //stack is empty
S.head = n //new node is the head of the linked list
S.top = n //new node is the also the top
else
S.top.next = n
S.top = n

Similarly, to remove a node (pop), we will first check if the stack is empty or not as we did in the
implementation with array.

POP(S)
if IS_EMPTY(S)
Error “Stack Underflow”

In the case when the stack is not empty, we will first store the value in top node in a temporary
variable because we need to return it after deleting the node.

POP(S)
if IS_EMPTY(S)
...
else
x = S.top.data

Now if the stack has only one node (top and head are same), we will just make
both top and head null.

POP(S)
if IS_EMPTY(S)
...
else
...
if S.top == S.head //only one node
S.top = NULL
S.head = NULL
If the stack has more than one node, we will move to the node previous to the top node and make
the next of point it to null and also point the top to it.
POP(S)
...
...
if S.top == S.head //only one node
...
else
tmp = S.head
while tmp.next != S.top //iterating to the node previous to top
tmp = tmp.next
tmp.next = NULL //making the next of the node null
S.top = tmp //changing the top pointer

We first iterated to the node previous to the top node and then we marked its next to null -
tmp.next = NULL. After this, we pointed the top pointer to it - S.top = tmp.
At last, we will return the data stored in the temporary variable - return x.

POP(S)
if IS_EMPTY(S)
Error "Stack Underflow"
else
x = S.top.data
if S.top == S.head //only one node
S.top = NULL
S.head = NULL
else
tmp = S.head
while tmp.next != S.top //iterating to the node previous to top
tmp = tmp.next
tmp.next = NULL //making the next of the node null
S.top = tmp //changing the top pointer
return x
PROGRAM :

#include <stdio.h>
#include <stdlib.h>

typedef struct node {


int data;
struct node *next;
}node;

typedef struct linked_list {


struct node *head;
struct node *top;
}stack;

//to make new node


node* new_node(int data) {
node *z;
z = malloc(sizeof(struct node));
z->data = data;
z->next = NULL;

return z;
}

//to make a new stack


stack* new_stack() {
stack *s = malloc(sizeof(stack));
s->head = NULL;
s->top = NULL;

return s;
}

void traversal(stack *s) {


node *temp = s->head; //temporary pointer to point to head

while(temp != NULL) { //iterating over stack


printf("%d\t", temp->data);
temp = temp->next;
}

printf("\n");
}

int is_empty(stack *s) {


if(s->top == NULL)
return 1;
return 0;
}

void push(stack *s, node *n) {


if(is_empty(s)) { //empty
s->head = n;
s->top = n;
}
else {
s->top->next = n;
s->top = n;
}
}

//function to delete
int pop(stack *s) {
if(is_empty(s)) {
printf("Stack Underflow\n");
return -1000;
}
else {
int x = s->top->data;
if(s->top == s->head) {// only one node
free(s->top);
s->top = NULL;
s->head = NULL;
}
else {
node *temp = s->head;
while(temp->next != s->top) // iterating to the last element
temp = temp->next;
temp->next = NULL;
free(s->top);
s->top = temp;
}
return x;
}
}

int main() {
stack *s = new_stack();

node *a, *b, *c;


a = new_node(10);
b = new_node(20);
c = new_node(30);
pop(s);
push(s, a);
push(s, b);
push(s, c);
traversal(s);
pop(s);
traversal(s);
return 0;
}
VI . INFIX, PREFIX & POSTFIX NOTATIONS :

Definition of Infix, Postfix, and Prefix.

Infix Prefix Postfix


A+B +AB AB+
A+B-C -+ABC AB+C-
(A+B)*C-D -*+ABCD AB+C*D-

For writing complex mathematical expressions, we generally prefer parentheses to make them
more readable. In computers, expressions with various parentheses add unnecessary work while
solving. So, to minimize the computational works, various notations have been made. Prefix and
Postfix are one of them.

Definition of Infix, Postfix, and Prefix :

Infix: The typical mathematical form of expression that we encounter generally is known as
infix notation. In infix form, an operator is written in between two operands.

For example:
An expression in the form of A * ( B + C ) / D is in infix form. This expression can be simply
decoded as: “Add B and C, then multiply the result by A, and then divide it by D for the final
answer.”

Prefix: In prefix expression, an operator is written before its operands. This notation is also
known as “Polish notation”.

For example, The above expression can be written in the prefix form as / * A + B C D. This
type of expression cannot be simply decoded as infix expressions.

Postfix: In postfix expression, an operator is written after its operands. This notation is also
known as “Reverse Polish notation”.

For example, The above expression can be written in the postfix form as A B C + * D /. This
type of expression cannot be simply decoded as infix expressions.
Refer to the table below to understand these expressions with some examples:

Infix Prefix Postfix


A+B +AB AB+
A+B-C -+ABC AB+C-
(A+B)*C-D -*+ABCD AB+C*D-

Prefix and postfix notions are methods of writing mathematical expressions without parentheses.
Let’s see the infix, postfix and prefix conversion.

(i) Infix to Postfix Conversion:

In infix expressions, the operator precedence is implicit unless we use parentheses. Therefore, we
must define the operator precedence inside the algorithm for the infix to postfix conversion.
The order of precedence of some common operators is as follows:
Note: For detailed information on the order of precedence, you can check out C Operator
Precedence.

Algorithm:
o Create a stack.
o For each character c in the input stream:

If c is an operand
{
Output c
}
Else if c is a right parentheses
{
Pop and output tokens until a left parentheses is popped
}
Else
{ // c is an operator or left parentheses
Pop and output tokens until one of the lower priorities than c
are encountered, or a left parentheses is encountered, or the stack is empty.
Push c
}

o Pop and output tokens until the stack is empty.


For a better understanding, let’s trace out an example: A * B- (C + D) + E

Input Postfix
Operations on Stack Stack
Character Expression
A Empty A
* Push * A
B * AB
- Check and Push - AB*
( Push -( AB*
C -( AB*C
+ Check and Push -(+ AB*C
D AB*CD
Pop and Append to
) - AB*CD+
Postfix till ‘(’
+ Check and Push + AB*CD+-
E + AB*CD+-E
End Pop till Empty AB*CD+-E+

Implementation of the above algorithm:

#include<bits/stdc++.h>
using namespace std;

//precedence of operators
int precedence(char ch)
{
if(ch == '^')
return 3;
else if(ch == '/' || ch =='*')
return 2;
else if(ch == '+' || ch == '-')
return 1;
else
return -1;
}

string infixToPostfix(string s)
{
stack<char> st;
string postfix_exp;

for(int i = 0; i < s.length(); i++)


{
char ch = s[i];

// If the input character is


an operand, add it to the postfix output string. if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <=
'Z') || (ch >= '0' && ch <= '9'))
postfix_exp += ch;

// If the input character is an


'(', push it to the stack.
else if(ch == '(')
st.push('(');

// If the input character is an ')',


pop and output string from the stack
until an '(' is encountered.
else if(ch == ')') {
while(st.top() != '(')
{
postfix_exp += st.top();
st.pop();
}
st.pop();
}

//If the character is an operator


else
{
while(!st.empty() && precedence(s[i]) <= precedence(st.top()))
{
postfix_exp += st.top();
st.pop();
}
st.push(ch);
}}

// Pop all the remaining elements from the stack


while(!st.empty())
{
postfix_exp += st.top();
st.pop();
}
return postfix_exp;
}

int main()
{
string infix_expression = "A*B-(C+D)+E";
cout<<"The postfix string is: "<<infixToPostfix(infix_expression);
return 0;
}

Output:

The postfix string is: AB*CD+-E+

(ii) Prefix to Postfix Conversion :

Converting a prefix expression to a postfix expression is almost the same as the above
conversions. The one difference is that we’ll use stack to store operands this time.

Algorithm:
o Reverse the prefix string.
o Create a stack.
o For each character c in the input stream:

If c is an operand
{
Push it in the stack
}
Else
{ // c is an operator
Pop two tokens(operand) from the stack. Concatenate the operands and the operator, as (operand
1 + operand 2 + operator). And push this string back in the stack
}

Note: This string will now act as an operand.


o Repeat until the stack is empty or the input string ends.

For a better understanding, let’s trace out an example: * + A B – C D

Reversed String: D C – B A + *

Input Character Operation on Stack Stack-1(Postfix)


D Push D
C Push DC
– Concatenate and Push (CD-)
B Push (CD-) B
A Push (CD-) B A
+ Concatenate and Push (CD-) (AB+)
* Concatenate and Push (AB+) (CD-) *
End Final Output: AB+CD-*

Note: parentheses are only used to represent the string after concatenation.
Implementation of the above algorithm:

#include <bits/stdc++.h>
using namespace std;

// To check if character is operator or not


bool check_op(char x)
{
if(x =='+'|| x== '-'|| x== '/'|| x=='*')
return true;
else
return false;
}

// Convert prefix to Postfix expression


string prefixToPostfix(string str)
{
reverse(str.begin(), str.end());
stack<string> s;
int length = str.size();

for (int i = 0; i <length; i++)


{
if (check_op(str[i]))
{
string op1 = s.top();
s.pop();
string op2 = s.top();
s.pop();

string temp = op1 + op2 + str[i];

s.push(temp);
}
else
{

s.push(string(1, str[i]));
}
}

return s.top();
}

// Driver Code
int main()
{
string str1 = "*+AB-CD";
string str = prefixToPostfix(str1);
cout<<"The postfix string is: "<<str<<endl;
return 0;
}

Output:

The postfix string is: AB+CD-*


VII. EVALUATION OF POSTFIX, INFIX & PREFIX EXPRESSION :

Infix, Prefix and Postfix Expressions

Infix Expression Prefix Expression Postfix Expression


A+B*C+D ++A*BCD ABC*+D+
(A + B) * (C + D) *+AB+CD AB+CD+*
A*B+C*D +*AB*CD AB*CD*+
A+B+C+D +++ABCD AB+C+D+

Conversion of Infix Expressions to Prefix and Postfix


Introduction

 Operation : Any Expression of algebraic format (Example : A + B)


 Operands : A and B or 5 & 6 are operands
 Operators : +. -, %,*,/ etc are operators

Infix Notation
Infix is the day to day notation that we use of format A + B type. The general form can be
classified as (a op b) where a and b are operands(variables) and op is Operator.

 Example 1 : A + B
 Example 2 : A * B + C / D

Postfix Notation
Postfix is notation that compiler uses/converts to while reading left to right and is of
format AB+ type. The general form can be classified as (ab op) where a and b are
operands(variables) and op is Operator.

 Example 1 : AB+
 Example 2 : AB*CD/+

Prefix Notation
Prefix is notation that compiler uses/converts to while reading right to left (some compilers can
also read prefix left to right) and is of format +AB type. The general form can be classified as (op
ab) where a and b are operands(variables) and op is Operator.

 Example 1 : +AB
 Example 2 : +*AB/CD
Why Postfix/Prefix Expressions are faster than Infix?

For Infix Expression which is format A+B*C, if the compiler is reading left to right then it can’t
evaluate A+B first until it has read whole expression and knows expression is actually A +
(B*C) i.e. B * C needs to be implemented first

Postfix for above infix is ABC*+. Now, as soon as compiler sees two operands followed by
operator it can implement it without caring for precedence.

 Assume ABC*+
 ABC*+ (BC* is implemented as B*C and result is put back)
 AX+ (Assuming X stores result of BC* i.e. B*C)
 Now finally AX+ can be implemented as A+X

Note :
Compiler converts our Infix Expression into postfix or Prefix as expressions are operated as
stacks and postfix and prefix are faster to implement as compiler doesn't need to care about
precedence at all.

Compiler converts infix expression to postfix/prefix at compile time, so at runtime your


calculations are always happening in post-prefix. A website's code maybe compiled once a week
but it may need to run 1 million times a week.

Problem :
 Infix: a + b * c + d can be written as a + (b * c) + d
 Now, for all + – / * associativity is left to right we will write it as
 (a + (b * c)) + d and thus further ((a + (b * c)) + d)
 Solving and converting innermost bracket to postfix
 Step 1 –((a + bc*)+ d)
 Step 2 – Consider bc* as separate operand x the innermost bracket now looks like ((a
+ x)+ d)
o Applying postfix it looks like – (ax+ + d)replacing x here (abc*+ + d)
 Step 3 – Consideringabc*+as separate operand z, the final bracket looks like – (z + d)the
result would be zd+
o replacing z value = abc*+d+
Algorithm :

1. First Start scanning the expression from left to right


2. If the scanned character is an operand, output it, i.e. print it
3. Else
o If the precedence of the scanned operator is higher than the precedence of the
operator in the stack(or stack is empty or has'(‘), then push operator in the stack
o Else, Pop all the operators, that have greater or equal precedence than the scanned
operator. Once you pop them push this scanned operator. (If we see a parenthesis
while popping then stop and push scanned operator in the stack)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
6. Now, we should repeat the steps 2 – 6 until the whole infix i.e. whole characters are
scanned.
7. Print output
8. Do the pop and output (print) until stack is not empty

Infix to Prefix :
 Infix: (a / b + c) - ( d + e * f) can be written as ((a / b) + c) - ( d + (e * f))
 Now, we have done the above according to associativity
 Solving and converting innermost bracket to prefix
 Step 1 –(/ab + c) - ( d + *ef)
 Step 2 – Consider /ab and *ef as separate operand x and y
 the innermost bracket now looks like (x + c) - (d + y)
o Applying prefix it looks like – (+xc - +dy)replacing x and y here (+/abc - +d*ef)
 Step 3 – Considering+/abc and+d*efas separate operand z and w, the final bracket looks
like – (z - w)the result would be -zw
o replacing z and w value = -+/abc+d*ef
Given Infix : - ((a/b)+c)-(d+(e*f))

 Step 1: Reverse the infix string. Note that while reversing the string you must
interchange left and right parentheses.
 Step 2: Obtain the postfix expression of the expression obtained from Step 1.
 Step 3: Reverse the postfix expression to get the prefix expression

String after reversal : – ))f*e(+d(-)c+)b/a((

1. String after interchanging right and left parenthesis – ((f*e)+d)-(c+(b/a))


2. Apply postfix – Below is postfix (On this page you check infix to postfix
conversion rule)
3. Reverse Postfix Expression (Given After the image below)

Sr. No. Expression Stack Prefix

0 ( (

1 ( ((

2 f (( f

3 * ((* f

4 e ((* fe

5 ) ( fe*

6 + (+ fe*

7 d (+ fe*d

8 ) fe*d+

9 – – fe*d+

10 ( -( fe*d+

11 c -( fe*d+c

12 + -(+ fe*d+c

13 ( -(+( fe*d+c

14 b -(+( fe*d+cb
Sr. No. Expression Stack Prefix

15 / -(+(/ fe*d+cb

16 a -(+(/ fe*d+cba

17 ) -(+ fe*d+cba/

18 ) – fe*d+cba/+

19 fe*d+cba/+-

Final prefix : -+/abc+d*ef


VIII. APPLICATION OF STACK :

Applications of stack:
 Expression Evaluation.
 Expression Conversion. i. Infix to Postfix. ii. Infix to Prefix. iii. Postfix to Infix. iv. Prefix to
Infix.
 Backtracking.
 Memory Management.

Applications of Stack in Data Structure:


o Evaluation of Arithmetic Expressions
o Backtracking
o Delimiter Checking
o Reverse a Data
o Processing Function Calls

You might also like