0% found this document useful (0 votes)
33 views45 pages

Bca Unit 3 Data Structures

au bca data stryctures
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views45 pages

Bca Unit 3 Data Structures

au bca data stryctures
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Unit- III

Linked Lists – Representation, Dynamic Memory Allocation, Traversing, Searching,


Insertion, Deletion, Header Linked Lists, Two-Way Lists
Stacks- Stacks, Operations on stacks, Array representation of stacks, Linked List
representation of stacks, Arithmetic Expressions, Polish notation, Recursion.

DEPARTMENT OF COMPUTER SCIENCE


SPACES DEGREE COLLEGE
PAYAKARAOPETA

1
Q) Write short notes on Dynamic Memory allocation? (5m)
Dynamic Allocation: Allocation of memory to variables at run-time is known as
dynamic memory allocation. C provides four functions to allocate memory at runtime.
They are
1. malloc( ): Allocates a block of memory of particular size at runtime and returns a
pointer of void type.
Syntax: ptrvar=(type*)malloc(bytesize);
Eg: p=(int *) malloc(sizeof(int));

2. calloc ( ): Allocates array of memory dynamically and initializes them to zero. It


returns pointer of void type.
Syntax: ptrvar=(type*)calloc(n, bytesize);
Eg: p=(int *) calloc(5,sizeof(int));

3. realloc( ): It alters the size of allocated memory allocated by malloc() or calloc()


Syntax:ptr=realloc(ptr,newsize);
Eg: p=realloc(p,3*sizeof(int));

3. free( ): It is used to free the memory space allocated by malloc( ),calloc( ) or


realloc( )
Syntax: free(ptr);
Eg: free(p);

Q) What is Linked List? Explain different types of Linked


lists.(****Vimp***)
 List is a linear collection of data items or elements.
 Linked List is a linear data structure, in which the elements are not stored at
contiguous memory locations. Each element in linked list is represented using Nodes.
 Linked List is also defined as collection of Nodes.
 Each Node in linked list contains data field to store similar elements and next field to
store the address of next node.
 The elements in linked lists are connected via pointers
 Linked lists follows RIRO (Random-In Random-Out) organisation, in which the
elements can be inserted or deleted at first, last or at anywhere from the list.
Advantages of linked lists:

1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the
execution of a program.
2. Linked lists have efficient memory utilization. Memory is allocated whenever it is
required and it is de-allocated (removed) when it is no longer needed.

2
3. Insertion and Deletions are easier and efficient. Elements can be inserted or deleted at
first, last or anywhere in the list.
4. Many complex applications can be easily carried out with linked lists.

Disadvantages of linked lists:


1. It consumes more space because every node requires a additional pointer to store address of
the next node.
2. Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.
Single Linked List:
 It is a linked list in which all the nodes are linked together in some sequential manner.
 It is also known as Linear Linked List.
 In this, each node has successor except the last node.
 In linear or single linked list a node is connected to next node using a single link.
 In this , the elements are traversed in forward direction only.
Structure of node:

Data field - contains data item


Next – contains link(pointer) to next node

Structure of node is defined as

3
Double Linked List:
 It is a linked list in which all the nodes are linked together by multiple
links , which helps in accessing both successor(next) node and
predecessor(previous) node.
 Each node in double linked list has two links, one points to address of
next node and other points to address of previous node.
 In this, the elements can be traversed in both forward & backward
direction.
Structure of node:

It has three parts


1. Data field – contains the data items.
2. Prev - contains the address of the previous node in the list
3. Next - contains the address of the next node in the list.

Example:

Circular Linked List:


 It is a linked list in which the last node is connected to the first node.
 In this , each node has successor.
 Each node in circular linked contains data part to store elements and next
part to store the address of next node.
4
 In this, the elements can be traversed in forward direction only.
Structure of node:

It has two parts


a. Data – contains the data items.
b. Next - contains the address of the next node in the list

Eg:

Q) What is Single Linked List? Explain various operations


performed on Single Linked List? .(****Vimp***)
(OR) Explain about insertion and Deletion operations in Single
Linked List.
 Linked List is a linear data structure, in which the elements are not
stored at contiguous memory locations. Each element in linked list is
represented using Nodes.
 Linked List is also defined as collection of Nodes.
 Single linked list in which all the nodes are linked together in some
sequential manner.
 It is also known as Linear Linked List.
 In this, each node has successor except the last node.
 In linear or single linked list, a node is connected to next node using a
single link.
 In this , the elements are traversed in forward direction only.
Structure of node:

Data - contains data item.


Next - contains link(pointer) to next node.

5
Basic operations on single linked list:
1.creation: To create an empty linked list.
Algorithm:
Start
1. Define the structure Node, that contains data field and Next Field.
2. Declare a pointer L of Node type
3. Set L=NULL

Code:
struct node
{
int data;
struct node *next;
};
struct node *L=NULL;

2.INSERTION: Adding an element into singly linked list is known as Insertion


operation.

Insertion of elements into single linked list can be done in 3 ways.

a) Inserting an element at beginning of list


b) Inserting an element at Last of list.
c) Inserting an element after specific location.

Inserting an element at beginning of list

Algorithm: beginsert(int x)
start
1. Create a new node temp
2. Set temp->data=x
6
temp->next=L
3. L=temp

End

Inserting an element at last of list

Algorithm: lastinsert (int x)


Start
7
1. Create a new node temp
2. a) Set temp->data=x
b) temp->next= NULL
3. If L=NULL then
a) L=temp
b) Go to End
4. L1=L
5. While (L1->next!=NULL)
L1=L1->next
6. L1->next=temp

Inserting an element after specific location:

Algorithm : afterinsert(int x).


Start
1. Read location to LOC
2. Create a new node Temp
3. Set Temp->data=x
Temp->next=NULL
4. IF L=NULL then
a) L=temp
b) Go to End
5. L1=L
6. For i = 1 to LOC-1
L1=L1->Next
7. Temp->next=L1->next
8. L1->next=Temp
End

3. DELETION:
It is used remove a node from a list. The deletion operation can be performed in three ways.
They are
 Deleting beginning Element from the list
 Deleting last Element from the list
 Deleting Specific element from the list
Deleting an element from beginning of list

8
Algorithm: begdelete()
1. If L=NULL then
a) Print “ No elements”
b) Go to end
2. temp=L;
3. L=temp->next;
4. free(temp);

Deleting Last element from List

Algorithm: lastdelete( )
1. If L=NULL then
c) Print “ No elements”
d) Go to end
2. Temp=L
3. If temp->next !=NULL
a) L1=Temp
b) Temp=temp->next
c) Go to step 3
4. L1->next=NULL
5. Print temp->data “ is deleted”
6. Free(temp)

9
Deleting specific element from List
Algorithm: deleteelement( x)
1. If L=NULL then
a) Print “ No elements”
b) Go to end
2. IF (L->data=x) then
1) L=L->next
2) Go to end

3. temp=L

4. while(temp->data!=x)
a) L1=temp
b) temp=temp->next
5. L1->Next = Temp->next
6. Free (temp)

4.Traverse:

It is used to visit or print the elements in the list.

Algorithm: traverse( )

Start
1. If L=NULL then
a) Print “no elements”
b) Go to end
2. Temp = L
3. If temp!=NULL Then
a) Print “ temp->data”
b) Temp=temp->next
c) Go to step 3

Q) What is Double Linked List? Explain various operations performed on Doubly


Linked List? .(****vImp***)
Double Linked List:
 It is a linked list in which all the nodes are linked together by multiple links , which
helps in accessing both successor(next) node and predecessor(previous) node.
 Each node in double linked list has two links, one points to address of next node and
other points to address of previous node.
10
 In this, the elements can be traversed in both forward & backward direction.
Structure of node:

It has three parts


1. Data field – contains the data items.
2. Prev - contains the address of the previous node in the list
3. Next - contains the address of the next node in the list.

Basic operations on Doubly linked list:


1. creation
2. Insertion
3. Deletion
4. Traverse
1.creation: To create an empty linked list.
Algorithm:
Start
1. Define the structure Node, that contains data field, previous Field and Next Field.
2. Declare a pointer L of Node type
3. Set L=NULL
End
Code:
struct node
{
struct node *prev;
int data;
struct node *next;
};
struct node *L=NULL;

2.INSERTION: Adding an element into Doubly linked list is known as Insertion operation.

Insertion of elements into doubly linked list can be done in 3 ways.

1. Inserting an element at beginning of list


2. Inserting an element at Last of list.
3. Inserting an element after specific location.
11
Inserting an element at beginning of list

Algorithm: beginsert (int x)


start
1. Create a new node temp
2. Set Temp->prev=NULL
Temp->data=x
Temp->next=L
3. If L!=NULL
L->prev=temp
4. L=temp
End

Inserting an element at last of list

Algorithm : lastinsert(int x)
Start
1. Create a new node Temp
2. Set Temp->prev=NULL
Temp->data=x
Temp->next=NULL
3. if L = NULL then
a) L=temp
b) Go to End

4. L1=L
5. While L1->Next !=NULL
L1=L1->next
6. L1->NEXT=TEMP
7. TEMP->PREV=L1
end
Inserting, an element after specific location:

Algorithm : afterinsert(int x)
Start
1. Read insert Location to Loc
2. Create a new node temp
3. Set temp->prev=NULL
12
temp->data=x
temp->next= NULL
4. if L = NULL then
c) L=temp
d) Go to End
5. If loc > count
a) Print “ can’t able to insert the node”
b) Go to End
6. L1=L
7. For i=1 to Loc-1
L1=L1->next
8. Temp->next=L1->next
9. Temp->next->prev=temp
10. L1->next = temp
11. Temp->prev=L1
End
3. DELETION:
It is used remove a node from a double linked list. The deletion operation can be performed in
three ways. They are
 Deleting beginning Element from the list
 Deleting last Element from the list
 Deleting Specific element from the list

Deleting an element from beginning of list

Algorithm: begdelete()
1. If L=NULL then
a) Print “ No elements”
13
b) Go to end
2. temp=L
3. L=L->next
4. If L!=NULL
L->prev=NULL
5. Free(temp)

Deleting Last element from List

Algorithm: lastdelete( )
1. If L=NULL then
a) Print “ No elements”
b) Go to end
2. Temp=L
3. If temp->next !=NULL
a) Temp=Temp->next
b) Go to step 3
4. Temp->prev->next=NULL
5. Print temp->data “ is deleted”
6. Free(temp)

Deleting specific element from List


Algorithm: deleteelement( x)
1. If L=NULL then
c) Print “ No elements”
d) Go to end
2. temp=L
3. IF (L->data=x) then
a) L=L->next
b) If Temp->next !=NULL then
I) L->prev=NULL
c) free(Temp)

4. if(temp->data!=x)
a) L1=temp

14
b) temp=temp->next
c) goto step 4

5. L1->Next = Temp->next
6. If (Temp->next!=NULL)
Temp->next->prev=L1
7. Free (temp)

4.TRAVERSE:
Traversing means visiting each element in the list. Double linked list Supports both forward
and Backward Traversing.
Algorithm: traverse()
1. If L=NULL then
a) Print “ list is empty”
b) Goto end
2. Temp=L
3. If Temp!=NULL then
a) L1=Temp
b) Print Temp->data
c) Temp=Temp->next
d) Goto step 3
4. If (L1!=NULL)
a) Print L1->data
b) L1=L1->prev
c) Goto step 4
end
Q) Explain the Advantages of Double linked list over single Linked List? (**5m**)
 In double linked lists we perform both forward and backward traversing where
as in single linked list only forward traversing is possible.
Eg:

Forward Traversing : 1 5 7
BackWard Traversing : 7 5 1
 Reversing the doubly linked list is very easy when compared to single linked list.
 Double linked list implementation is easy when compared to single linked list..
15
 Deletion of nodes in double linked list is easy as compared to a Singly Linked
List.

Q) What is Circular Linked List? Explain various operations performed on Circular


Linked List?
 Circular Linked List is a linked list in which the last node is connected the first node. In
this, each node has successor.

 In Circular linked list, each node is connected to next node using a single link.

Structure of Node:

Data - contains data item.


Next - contains link(pointer) to next node.

Basic operations on circular linked list:


1. creation
2. Insertion
3. Deletion
4. Traverse
1.creation: To create an empty circular linked list.
Algorithm:
Start
1. Define the structure Node, that contains data field and Next Field.
2. Declare a pointer L of Node type
3. Set L=NULL
16
2. INSERTION: Adding an element into circular linked list is known as Insertion operation.
Inserting elements into circular linked list can be done in 3 ways.

1. Inserting an element at beginning of list


2. Inserting an element at Last of list.
3. Inserting an element after specific location.

Inserting an element at beginning of list

Algorithm: beginsert(int x)
start
1. Create a new node temp
2. Set Temp->data=x
Temp->next=NULL
3. L1=L
4. While(L1->next !=L)
L1=L1->next
5. L1->next=temp
6. Temp->next=L
7. L=Temp

Inserting an element at last of list

Algorithm: lastinsert(int x)

start
1. Create a new node temp
2. Set Temp->data=x
Temp->next=NULL
3. L1=L
4. While (L1->next!=L)
L1=L1->next
5. L1->next=temp
6. Temp->next=L

Inserting an element after specific location:

Algorithm : afterinsert(int x)
Start
1. Create a new node temp
2. Set Temp->data=x
Temp->next=NULL
17
3. Read location to LOC
4. L1=L
5. For i=0 to LOC-1
L1=L1->next
6. Temp->next=L1->next
7. L1->next=Temp

3. DELETION:
It is used remove a node from a circular linked list. The deletion operation can be performed
in three ways. They are
 Deleting beginning Element from the list
 Deleting last Element from the list
 Deleting Specific element from the list

Deleting an element from beginning of list

Algorithm: begdelete( )
start
1. If L=NULL then
c) Print “ No elements”
d) Go to end
2. Temp=L
18
3. If L->next=L then
a) L=Null
b) Free(temp)
c) Goto end
4. L1=L
5. while L1->next!=L then
L1=L1->next
6. L1->next=L->next
7. L=L1->next
8. Free(temp)
Deleting an element at Last of list
Algorithm: lastdelete( )
start
1. If L=NULL then
a) Print “ No elements”
b) Go to end
2. Temp=L
3. If L->next=L then
a) L=Null
b) Free(temp)
c) Goto end

4. while Temp->next! =L then


a) L1=Temp
b) Temp=Temp->next
5. L1->next=Temp->next
6. Free(temp)
Deleting specific element from List
Algorithm: deleteelement( x)
1. If L=NULL then
a) Print “ No elements”
b) Go to end
2. Temp=L
3. If L->data=x and L->next=L Then
a) L=NULL
b) Free(temp)
c) Goto end

4. If L->data=x then
a) L1=L
b) While L1->next!=L
L1=L1->next
c) L=L->next

19
d) L1->next=L
e) Free(Temp)
f) Go to end
5. If Temp->data!=x then
a) L1=Temp
b) Temp=Temp->next
c) Goto 5
6. L1->next=Temp->next
7. Free(Temp)

4.TRAVERSE:
Traversing means visiting each element in the list. Double linked list Supports both forward
and Backward Traversing.
Algorithm: traverse()
1. If L=NULL then
a) Print “ list is empty”
b) Goto end
2. Temp=L
3. While Temp->next!=L
a. Print Temp->data
b. Temp=Temp->next
4. Print Temp->data

23 36 72 82

Q) Explain about header linked list ?


 A header linked list is a special type of linked list which consists of a header node in
the beginning of the list.
 The header node can store meta data about the linked list.
 This type of list is useful when information other than that found in each node is
needed.

20
There are two types of header linked lists
1. Singly or Doubly Header Linked List
2. Singly or Doubly Circular Header Linked List
1. Singly or Doubly Header Linked List
1. It is a list whose last node contains the NULL pointer.
2. In the header linked list the start pointer always points to the header node.
3. start -> next = NULL indicates that the header linked list is empty.
4. The operations that are possible on this type of linked list are Insertion, Deletion, and
Traversing.

Algorithm:
Start
Step 1:Initialize the Header Linked List
header->next = NULL
Start
1. Create a new node temp.
2. Set temp->data = x and temp->next = NULL.
3. Initialize a pointer current = header.
4. Traverse the list until current->next = NULL.
5. Set current->next = temp.
End

2. Singly or Doubly Circular Header Linked List


21
1. A list in which the last node points back to the header node is called circular header
linked list.
2. The chains do not indicate first or last nodes. In this case, external pointers provide a
frame of reference because last node of a circular linked list does not contain the NULL
pointer.
3. The possible operations on this type of linked list are Insertion, Deletion and
Traversing.

Algorithm:
1. Create a node header.
2. Set header->next = header to make it circular.
3. Input: Data x to insert at the end.
Start
4. Create a new node temp.
5. Set temp->data = x and temp->next = header.
6. Initialize a pointer current = header.
7. Traverse the list until current->next == header.
8. Set current->next = temp.
End

Q) Explain about linked lists in Arrays?


Array is a group of consecutive memory locations which stores homogenous type of data.
To implement the linked list in Arrays we require two arrays. They are
1. Ele[i] – to store the data items
2. Next[i] – to store the address of elements but not physical address
We also use the following variables
22
Free variable to specify the no of locations used in array
Start variable to specify the beginning element position.

The first element is added to Ele[0] and Next[0] remains -1

The second element is added to Ele[1] and Next[1] =1

Similarly add Ele[2]=-5, Ele[3]=0, Ele[4]=99 elements is added and set Next[2] =2,
Next[3]=3, Next[4]=-1(last element in list)

23
Add another node

Q) Differentiate between Linked List and Arrays (or) Linked List Versus
Arrays?(*****5m or Essay***)

LINKED LIST ARRAYS


1. Collection of nodes Linked via 1. Collection of consecutive
pointers memory locations that stores
homogenous or same type of
data.
2. Pointer is used to access next 2. Subscript is used to access the
element. next element.
3. Access elements in sequential 3. Access elements in random
order. order.
4. Elements are Stored in random 4. Elements are Stored in
memory locations. contagious memory locations.
5. It is dynamic list. 5. It is a static list.

24
6. It is possible to grow or shrink 6. It is not possible to
the size of the list. increase/decrease the size of the
array.
7. While inserting or deleting the 7. While inserting or deleting we
elements we need not change need to change the positions of
positions. elements.
8. Memory shortage will not occur 8. Memory shortage may occur
as the elements are stored when there are contiguous
randomly. locations.
9. It uses single, double , circular 9. It has single , 2D ,multi-
list Dimensional arrays

Q) Explain about STACK as ADT (OR) Explain about various operations on


STACK? (OR) Explain about the Representation of stacks using Arrays?
(****VIMP*****)

 Stack is a linear data structure in which elements are inserted and deleted from one end
called Top end.
 It follows LIFO(Last-In First-Out) organisation. In this the last element inserted is the
first element to be deleted.
 In stack, the insertion operation is known as PUSH and the deletion operation is known
as POP.
 Stack is an Abstract Data Type (ADT) and has the following operations.
1. Creation of empty stack

2. Determine whether stack is empty or not

3. Determine whether stack is full or not

4. If stack is not full, PUSH an element into stack from Top end

5. If stack is not empty, POP an element from stack at its Top .

6. If stack is not empty, Traverse the elements in the stack

7. If stack is not empty, retrieve the top element.

25
26
STACKS REPRESENTATIONS: Stacks can be represents using two data structures. They
are
1. Array representation: It is used to represent stacks of fixed size
2. Linked representation: It is used to represent stacks of variable size.
Operations of stacks using arrays:
1. creation()

2. isempty()

3. isfull()

4. push(int x)

5. pop()

6. peep()

7. traverse()

Algorithms for Stack


1. Creation (): This Operation is used to create an empty Stack

Start
1: Read size of the stack to "maxsize".
2: Create an array s[maxsize].
3: Set top= -1. End
2. isempty():This function is used to check whether stack is empty (or) not

Start
1: if (top==-1) then
Print “stack is empty”
[otherwise]
Print “stack is not empty”
End

27
3. isfull():This function is used to check whether the stack is full (or) not

Start
1: if (top==maxsize-1) then
Print “stack is full”
[otherwise]
Print “stack is not full”
End

4. push (int x): Before inserting an element into the stack we check whether the stack is
full or not. If it is full i.e Top>=maxsize-1 then overflow condition occurs otherwise
the element is inserted at the top position. This operation of the stack is called Push.
Start
1: Read an element x
2: if(top==maxsize-1)
a) Print "stack is overflow"

b) Go to end

3: set top=top+1
4: s[top]=x.
End

28
5. pop (): Before deleting an element from stack we check whether stack is empty or not. If it
is empty i.e., top=-1 then “under flow” condition occurs otherwise the element at top position
is deleted. This operation of stack is known as “POP”
Start
1) If (top= -1)

i. Print “under flow”

ii. Goto end

2) x = s[top]

3) top = top -1

4) print x is deleted

End
6. peep (): It is used to find the top most element in stack.
Start
1. If (top= -1)

a) Print “under flow”

b) Goto end

2. Print s[top]

End
7. traverse (): It is used to print the elements in stack from top to bottom.
Start 1) If (top= -1)
a) Print “under flow”

b) Goto end

2) Set i=top

3) If i>=0 then

i) print s[i]

ii) i=i-1

iii) goto 3 33 22 1
29
Q) Explain various operations of Linked Stack? (OR) Explain about the
Representation of Stacks using Linked Lists? (****VIMP****)
Stack is a linear data structure in which elements are inserted and deleted from
one end called Top end.
It follows LIFO(Last-In First-Out) organisation. In this the last element inserted
is the first element to be deleted.
In stack, the insertion operation is known as PUSH and the deletion operation is
known as POP.
The stacks which are represented using linked lists is known as Linked Stack.
Operations:
1. creation()

2. isempty()

3. push(int x)

4. pop()

5. traverse()

ALGORITHMS FOR LINKED STACK:

1. Creation (): It is used to create an empty stack

Start
1. Create a Node structure with two fields Data & Next.

2. Create a pointer TOP of type Node

3. Set TOP=NULL

End

30
2. isempty (): It is used to check whether stack is empty or not.

Start
1. If (TOP=NULL) then Display “stack is empty” Else
Display “stack is not empty”
End

3. push (int x): This operation is used to add an element into the linked stack

Start
1. Create a new Node Temp

2. Set Temp->data=x and Temp->next=NULL

3. If (TOP==NULL) Then

a) TOP=Temp

b) Go to End

4. temp->next=TOP

5. TOP=Temp [end-if]

4. pop (): This operation is used to delete an element from the linked stack

Start
31
1. If (TOP==NULL) Then

a) Print “Stack is Empty”

b) Go to End

2. Set Temp=TOP

3. TOP = TOP->next

4. Print Temp->data is deleted

5. Free (Temp) [end-if]

End

32
5. Traverse (): It is used to print the elements from Top to bottom.

Start
1. If (TOP==NULL) Then

a) Print “ Stack is Empty”

b) Go to End [otherwise]

2. Set Temp=TOP

3. While Temp!=NULL

a) Print Temp->data

b) Temp=Temp->next [end-if]

End

44 33 22 11

33
Explain about the Applications of Stacks? (5m) (*****VVVVIMP*********)
 Stack is a linear data structure in which elements are inserted and deleted from
one end called Top end.
 It follows LIFO (Last-In First-Out) organisation. In this the last element inserted
is the first element to be deleted.
Applications of stacks:

1) Stacks are used in recursion for storing immediate(temporary) values

2) The stack is used in DFS (Depth first Search)

3) Stack is used in converting Infix to postfix expressions

4) Stack is used in converting infix to prefix expressions.

5) The stack is used in evaluation of postfix expressions

6) The stack is used in evaluation of prefix expressions

7) It solves back tracking programs

8) Stacks are used to convert decimal number to binary number.

9) Stacks can be used to check parenthesis matching in an expression.

10) It is used to implement Undo and Redo operations

Q) Explain how to covert Infix to Postfix (reverse-polish notation)


Expression? (****VIMP***)

The algorithm transforms the given infix expression into postfix expression. This algorithm
uses stack to hold the operators & left parenthesis temporarily.
Algorithm to convert Infix to Postfix
Let, X is an infix expression and Y be the postfix expression.
1. Scan infix expression from left to right and repeat Step 2 to 6 for each element of infix
expression.
34
2. If an operand is encountered, add it to postfix expression Y.

3. If a left parenthesis is encountered, push it onto Stack.

4. If an operator is encountered, then:

a) If incoming operator priority is same or lower than the operator at top then
Repeatedly pop from Stack and add to postfix expression Y
b) If stack is empty or incoming operator priority is greater than operator at top
then Add operator to Stack.
5. If a right parenthesis is encountered, then:

a) Repeatedly pop from Stack and add to postfix expression Y until a left
parenthesis is encountered.
b) Remove the left Parenthesis.

6. Repeatedly pop from stack until stack is empty and add it postfix expression Y.

35
Program for infix to postfix
#include<stdio.h> #include<ctype.h> char s[100];
int top=-1;
int isoperator(char ch)
{
if ((ch=='*') ||(ch=='+') || (ch=='-') ||(ch=='/')) return(1);
else return(0);
}
void push(char ch)
{
top=top+1; s[top]=ch;
}
int pop()
{
char x1; x1=s[top];

top--; return(x1);
}
int priority(char ch)
{
if(ch=='(') return 0;
if(ch=='+'||ch=='-') return 1;
if(ch=='*' ||ch=='/') return 2;
}
main()
{
36
char exp[100], ch,x; int i=0;
puts("enter infix expression"); gets(exp);
ch=exp[i];
while (ch!='\0')
{
if (isalnum(ch)) printf("%c", ch);
else if(ch=='(') push(ch);
else if (isoperator(ch)==1)
{
while((priority(s[top])>=priority(ch))&&(top!=-1))
{
x=pop(); printf("%c",x);
}
push(ch);
}
else if (ch==')')
{
x=pop(); while(x!='(')
{
printf("%c",x); x=pop();
}
} i++;
ch=exp[i];
}
while(top!=-1)
{
x=pop(); printf("%c",x);
}
37
}

Q) Explain how to convert Infix to Prefix (polish notation) Expression?

The algorithm transforms the given infix expression into prefix expression. This algorithm
uses stack to hold the operators & left parenthesis temporarily.
Algorithm to convert Infix to Postfix
Let, X is an infix expression and Y be the prefix expression. 1.Reverse the given Infix
Expression.
2. Scan expression from left to right and repeat Step 3 to 6 for each element of infix
expression.
3. If an operand is encountered, add it to prefix expression Y.

4. If a right parenthesis is encountered, push it onto Stack.

5. If an operator is encountered, then:

a) If incoming operator priority is same or higher than the operator at top then
Repeatedly pop from Stack and add to prefix expression Y
b) Add operator to Stack.

6. If a left parenthesis( ) ) is encountered, then:

a) Repeatedly pop from Stack and add to prefix expression Y until a right
parenthesis ( ( ) is encountered.
b) Remove the right Parenthesis.

7. Repeatedly pop from stack until stack is empty and add it prefix expression Y.

8. Reverse the output expression.

38
Q) Explain about the Evaluation of Postfix Expression? (5m)

1. Read an element from postfix expression and For each element of postfix expression
repeat step 2 to step 3
2. If element is operand, then

Push the element into the stack


3. If the element is operator, then

a) Pop two operands from the stack

b) Evaluate the expression with two operands and with operator

c) Push the result into stack

4. If no more elements pop the result from stack else goto step 1

39
40
Q) Explain about the Evaluation of prefix Expression (5m)

1. Read an element from postfix expression and reverse it

2. For each element of prefix expression repeat step 3 to step 4

3. If element is operand, then

Push the element into the stack


4. If the element is operator, then

d) Pop two operands from the stack

e) Evaluate the expression with two operands and with operator

f) Push the result into stack

5. If no more elements pop the result from stack else goto step 1

EXAMPLE:

REVERSE OF PREFIX: DC+B*A+

41
42
43
Q) What is Recursion? Explain about it
 Recursion is the process of calling the same function within itself any no of times.
 Stacks are used to implement recursive procedures and transforming recursive
procedures to non-recursive procedures.
 It is used to solve complex algorithms like towers of honai, merge sort, quicksort etc
Characteristics of Recursive Function
1. Each time a function calls to itself must be closer to the solution

2. There must be some condition to stop the process of computation; otherwise, it may
result in infinite loop.
Every recursive solution has two cases. They are
 Base Case – In this, the problem is simply solved directly without making further
calls
44
Eg: if n==0
return 1;
 Recursive Case – In this , the problem is solved by calling the same function within
itself any
no of times
Eg: return n * fact(n-1)
Example:
int fact (int n)
{
If (n==0)
return(1);
Else return(n*fact(n-1));
}

45

You might also like