DSA Module 1
DSA Module 1
Module I
LINEARDATASTRUCTURES- LIST
Introduction, Data structure Types - Data structure operations - Abstract Data Types (ADTs) –
List ADT – array-based implementation – linked list implementation ––singly linked lists-–
applications of lists –Polynomial Manipulation - Stack ADT – Queue ADT - Evaluating
arithmetic expressions.
Data:
Acollectionoffacts,concepts,figures,observations,occurrencesorinstructionsinaFormalizedmanner.
Information:
Themeaning thatiscurrently assignedtodataby meansoftheconventionsappliedto those data
(i.e. processed data)
Record:
Collectionofrelatedfields.
Datatype:
Setofelementsthatsharecommonsetofpropertiesusedtosolveaprogram.
DataStructures:
DataStructureisthewayoforganizing,storing, andretrievingdataandtheirrelationship with each other.
Characteristicsofdatastructures:
1. Itdepictsthelogicalrepresentationofdataincomputermemory.
2. Itrepresentsthelogicalrelationshipbetweenthevariousdataelements.
3. Ithelpsinefficientmanipulationofstoreddataelements.
4. Itallowstheprogramstoprocessthedatainanefficientmanner.
OperationsonDataStructures:
1. Traversal
DATA STRUCTURE AND ALGORITHM
Module I
2. Search
3. Insertion
4. Deletion
CLASSIFICATIONOFDATASTRUCTURES
DATA STRUCTURES
PrimaryDataStructures /PrimitiveDataStructures:
Primitivedatastructuresincludeallthefundamentaldatastructuresthatcanbedirectlymanipulated by
machine-level instructions. Some of the common primitive data structuresinclude integer, character,
real, Boolean.etc
SecondaryDataStructures/NonPrimitiveDataStructures:
Non primitive data structures,refer to all those data structures that are derivedfrom one or more
primitive data structures. The objective of creating non-primitive data structures is to form sets of
homogeneous or heterogeneous data elements.
LinearDataStructures:
Linear data structures are data structures in which, all the data elements are arranged in linearor
sequential fashion. Examples of data structures include arrays, stacks, queues, linked lists, etc.
NonLinearStructures:
DATA STRUCTURE AND ALGORITHM
Module I
In non-linear data structures, there is definite order or sequence in which data elements are arranged.
For instance, a non-linear data structures could arrange data elements in a hierarchical fashion.
Examples of non-linear data structures are trees and graphs.
Staticanddynamicdatastructure:
StaticDS:
If a DS is created using static memory allocation,
ie.DS formed when thenumber of data items are known in advance ,it is known as static
data static ds or fixed size ds.
Dynamic DS:
Ifthe DS iscreatedusingdynamicmemory allocation
i.e DS formedwhenthenumberofdata items are not known in advance is known as dynamic ds or
variable size DS.
Applicationofdatastructures:
Datastructuresarewidelyappliedinthefollowingareas:
Compiler Design
Operating System
Statistical Analysis Package
DBMS
Numerical Analysis
Simulation
Artificial Intelligence
Graphics
ABSTRACTDATATYPES(ADT):
An abstract Data type (ADT) is defined as a mathematical model with a collection of operations
defined on that model. Set of integers, together with the operations of union, intersection and set
difference form a example of an ADT. An ADTconsists of data together with functions that operate on
that data.
Advantages/BenefitsofADT:
1. Modularity
2. Reuse
3. code is easier to understand
4. Implementation of ADTs can be changed without requiring changes to the program that
uses the ADTs.
THELISTADT:
DATA STRUCTURE AND ALGORITHM
Module I
Listisanorderedsetofelements.
ThegeneralformofthelistisA1,A2, ……,AN
A1-Firstelementofthe list
AN- Lastelement ofthe list
N–Size of the list
Iftheelementatposition i isAi,thenitssuccessorisAi+1anditspredecessorisAi-1
VariousoperationsperformedonList
1. Insert(X,5)-InserttheelementXaftertheposition5.
2. Delete(X)-TheelementXisdeleted
3. Find(X)-ReturnsthepositionofX.
4. Next(i)-Returnsthepositionofits successorelementi+1.
5. Previous(i)- Returnsthepositionofitspredecessori-1.
6. Printlist-Contents ofthe list is displayed.
7. Makeempty-Makesthelistempty.
ImplementationoflistADT:
1. ArraybasedImplementation
2. LinkedListbasedimplementation
ArrayImplementationoflist:
Array is a collection of specific number of same type ofdata stored in consecutive memory locations.
Arrayis a static data structure i.e., the memoryshould be allocated in advance and the size is fixed. This
will waste the memoryspace when used space is less than the allocated space.
Thebasicoperationsperformedonalistofelementsare
a. CreationofList.
b. InsertionofdataintheList
c. DeletionofdatafromtheList
d. Displayall data’sinthe List
e. Searchingforadata in thelist
Declarationof Array:
DATA STRUCTURE AND ALGORITHM
Module I
#define
maxsize 10
intlist[maxs
ize], n ;
Create Operation:
Create operation is used to create the list with ‘n’ number of elements .If‘n’ exceeds the
array’smaxsize, then elements cannot be inserted into the list. Otherwise the arrayelements are stored
in the consecutive arraylocations (i.e.) list [0], list [1] and so on.
void create()
{
cout<<"\n Enter the number of elements you want to create: ";
cin>>n;
cout<<"\nenter the elements\n";
for(i=0;i<n;i++)
{
cin>>b[i];
}
}
InsertOperation:
Insert operation is used to insert an element at particular position in the existinglist. Insertingthe
elementinthelastpositionofanarray iseasy.Butinserting the elementataparticularposition in an array is
quite difficult since it involves all the subsequent elementsto be shifted one position to the right.
Routinetoinsertanelementinthearray:
void insert()
{
cout<<"\nenter how many number u want to insert: ";
DATA STRUCTURE AND ALGORITHM
Module I
cin>>f;
cout<<"\nEnter the elements\n";
for(i=0;i<n;i++)
{
cin>>b[n++];
}
}
Consideranarraywith5elements[maxelements=10]
10 20 30 40 50
If data 15 is to be inserted in the 2nd position then 50 has to bemoved to next index
position, 40 has to bemoved to 50 position, 30 has to bemoved to 40 position and20 has
to bemoved to 30 position.
10 20 30 40 50
10 20 30 40 50
10 15 20 30 40 50
DeletionOperation:
Deletion is theprocess ofremovingan elementfrom thearrayat anyposition.
Deleting an element from the end is easy. If an element is to be deleted from any particular position,it
requires all subsequent element from that positionis shifted one positiontowardsleft.
DATA STRUCTURE AND ALGORITHM
Module I
Routinetodeleteanelementinthearray:
void deletion()
{
cout<<"Enter the number u want to delete \n";
cin>>d;
for(i=0;i<n;i++)
{
if(b[i]==d)
{
b[i]=0;
cout<
}
}
Consideranarraywith5elements[maxelements=10]
10 20 30 40 50
If data 20 is to be deleted from the array, then 30 has to be moved to data 20 position,
40 has to be moved to data 30 position and 50 has to be moved to data 40 position.
10 20 30 40 50
10 30 40 50
DisplayOperation/Traversingalist
Traversalistheprocessofvisitingtheelements ina array.
Display( ) operation is used to displayall the elements stored in the list. The elements are stored from
the index 0 to n - 1. Using a for loop, the elements in the list are viewed
DATA STRUCTURE AND ALGORITHM
Module I
Routinetotraverse/displayelementsofthearray:
Voiddisplay()
{
for(i=0;i<n;i++)
{
cout<<"\n"<<b[i];
}
SearchOperation:
Search( ) operation is used to determine whether a particular element is present in the list or not. Input
the search element to be checked in the list.
Routinetosearchanelementinthearray:
void search()
{
cout<<"Enter the number \n";
cin>>e;
for(i=0;i
{
if(b[i]==e)
{
cout<<"Value found the position\n"<
}}
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void create();
void insert();
void deletion();
void search();
void display();
inta,b[20],n,d,e,f,i;
void main()
{
int c;
clrscr();
cout<<"\n Main Menu";
cout<<"\n 1.Create \n 2.Delete \n 3.Search \n 4.insert \n5.Display \n 6.Exit";
do
{
cout<<"\n enter your choice:";
cin>>c;
switch(c)
{
DATA STRUCTURE AND ALGORITHM
Module I
case 1: create(); break;
case 2: deletion(); break;
case 3: search(); break;
case 4: insert(); break;
case 5: display(); break;
case 6: exit(0); break;
default:
cout<<"The given number is not between 1-5\n";
}
}
while(c<=6);
getch();
}
void create()
{
cout<<"\n Enter the number of elements you want to create: ";
cin>>n;
cout<<"\nenter the elements\n";
for(i=0;i<n;i++)
{
cin>>b[i];
}
}
void deletion()
{
cout<<"Enter the number u want to delete \n";
cin>>d;
for(i=0;i<n;i++)
{
if(b[i]==d)
{
b[i]=0;
cout<
}
}
}
void search()
{
cout<<"Enter the number \n";
cin>>e;
DATA STRUCTURE AND ALGORITHM
Module I
for(i=0;i<n;i++)
{
if(b[i]==e)
{
cout<<"Value found the position\n"<
}
}
}
void insert()
{
cout<<"\nenter how many number u want to insert: ";
cin>>f;
cout<<"\nEnter the elements\n";
for(i=0;i<n;i++)
{
cin>>b[n++];
}
}
void display()
{
for(i=0;i<n;i++)
{
cout<<"\n"<<b[i];
}
}
Advantagesofarrayimplementation:
1. Theelementsarefastertoaccessusingrandomaccess
2. Searching an element is easier
Limitationofarrayimplementation
Anarraystore its nodesin consecutivememorylocations.
Thenumber of elements in the arrayis fixed and it is not possible to change the number of
elements .
Insertion and deletion operation inarray are expensive. Since insertion is performed by pushing
the entire array one position down and deletion is performedby shifting theentire array one
position up.
Applicationsofarrays:
Arraysare particularlyused in programs that requirestoringlarge collection of similar type data
elements.
DifferencesbetweenArraybasedandLinkedbasedimplementation
DATA STRUCTURE AND ALGORITHM
Module I
Array LinkedList
Definition Array is a collection of elements having Linked list is an ordered collection of
same data type with common elements which are connected by
Name links/pointers
Access Elements can be accessed using Sequential access
index/subscript, random access
Memorystructure Elements are stored in contiguous Elements are store data available
memory locations memory space
Insertion&Deletion Insertion and deletion takes more time Insertion and deletion are fast and
in array easy
MemoryAllocation Memory is allocated at compile time Memory is allocated at runtime
i.e static memory allocation i.e dynamic memory allocation
Types 1D,2D,multi-dimensional SLL, DLL, circular linked list
Dependency Each elements is independent Each node is dependent on each
other as address part contains address
of next node in the list
Linkedlistbasedimplementation:
LinkedLists:
A Linked list is an ordered collection of elements. Each element in the list is referred as a node.
DATA NEXT
ALinkedlistnode
10 40 20 30
Null
AdvantagesofLinkedlist:
1. Insertionanddeletionofelementscanbedoneefficiently
2. Itusesdynamicmemoryallocation
DATA STRUCTURE AND ALGORITHM
Module I
3. Memoryutilizationisefficientcomparedto arrays
Disadvantagesof Linkedlist:
1. Linkedlistdoesnotsupportrandomaccess
2. Memory is required to store next field
3. Searchingtakestimecomparedtoarrays
As per the above illustration, following are the important points to be considered.
Linked List contains a link element called first.
Each link carries a data field(s) and a link field called next.
Each link is linked with its next link using its next link.
Last link carries a link as null to mark the end of the list.
Basic Operations
Following are the basic operations supported by a list.
Insertion − Adds an element at the beginning of the list.
Deletion − Deletes an element at the beginning of the list.
Display − Displays the complete list.
Search − Searches an element using the given key.
Delete − Deletes an element using the given key.
Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn this with diagrams
here. First, create a node using the same structure and find the location where it has to be inserted.
Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C (RightNode). Then
point B.next to C −NewNode.next −>RightNode;
It should look like this −
Now, the next node at the left should point to the new node.
LeftNode.next −>NewNode;
DATA STRUCTURE AND ALGORITHM
Module I
This will put the new node in the middle of the two. The new list should look like this −
Similar steps should be taken if the node is being inserted at the beginning of the list. While inserting it
at the end, the second last node of the list should point to the new node and the new node will point to
NULL.
Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial representation. First, locate
the target node to be removed, by using searching algorithms.
The left (previous) node of the target node now should point to the next node of the target node −
LeftNode.next −>TargetNode.next;
This will remove the link that was pointing to the target node. Now, using the following code, we will
remove what the target node is pointing at.
TargetNode.next −> NULL;
DATA STRUCTURE AND ALGORITHM
Module I
We need to use the deleted node. We can keep that in memory otherwise we can simply deallocate
memory and wipe off the target node completely.
Reverse Operation
This operation is a thorough one. We need to make the last node to be pointed by the head node and
reverse the whole linked list.
First, we traverse to the end of the list. It should be pointing to NULL. Now, we shall make it point to
its previous node −
We have to make sure that the last node is not the last node. So we'll have some temp node, which
looks like the head node pointing to the last node. Now, we shall make all left side nodes point to their
previous nodes one by one.
Except the node (first node) pointed by the head node, all nodes should point to their predecessor,
making them their new successor. The first node will point to NULL.
DATA STRUCTURE AND ALGORITHM
Module I
We'll make the head node point to the new first node by using the temp node.
Dynamicallocation
The process of allocating memory to the variables during execution of the program or at
run time is known as dynamic memory allocation. C language has four library routines
which allow this function.
SLLwith a Header
Basicoperationsonasingly-linkedlistare:
1. Insert–Insertsanewnodeinthelist.
2. Delete– Deletes anynodefrom the list.
3. Find – Findstheposition(address)ofanynode in the list.
4. FindPrevious-Findstheposition(address)ofthepreviousnodeinthelist.
5. FindNext-Finds theposition(address)ofthenextnodeinthelist.
6. Display-displaythe updateinthelist
7. Search-findwhetheraelementispresentinthelistornot
DeclarationofLinkedList
voidinsert(intX,ListL,positionP); void
find(List L,int X);
void delete(int x , List L);
typedefstruct node *position; positionL,p,newnode;
struct node
DATA STRUCTURE AND ALGORITHM
Module I
{
int data; positionnext;
};
Creationofthelist:
Thisroutinecreatesalistbygettingthenumberof nodesfromtheuser.
Assumen=4forthis example.
void create()
{
inti,n; L=NULL;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEnterthenumberofnodestobeinserted\n");
scanf("%d",&n);
printf("\n Enter the data\n");
scanf("%d",&newnode->data);
newnode->next=NULL;
L=newnode;
p=L;
for(i=2;i<=n;i++)
{
newnode=(structnode*)malloc(sizeof(structnode)); scanf("%d",&newnode->data);
newnode->next=NULL;
p->next=newnode;
p=newnode;
}}
RoutinetoDeletetheList
Thisroutinedeletedtheentirelist.
VoidDelete_list(List L)
{
PositionP,temp;
P=L->next;
L->next=NULL;
while(P!=NULL)
{
ctemp=P->next;
free(P); P=temp;
}}
DATA STRUCTURE AND ALGORITHM
Module I
void display()
{
struct Node* ptr;
ptr = head;
while (ptr != NULL)
{
cout<<ptr->data <<" ";
ptr = ptr->next;
}}
DATA STRUCTURE AND ALGORITHM
Module I
int main()
{
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: ";
display();
return 0;
}
Output
The linked list is: 9 2 7 1 3
In the above program, the structure Node forms the linked list node. It contains the data and a pointer
to the next linked list node. This is given as follows.
struct Node
{
int data;
struct Node *next;
};
The function insert() inserts the data into the beginning of the linked list. It creates a new_node and
inserts the number in the data field of the new_node. Then the new_node points to the head.
Finally the head is the new_node i.e. the linked list starts from there. This is given below.
void insert(intnew_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = head;
head = new_node;}
The function display() displays the whole linked list. First ptr points to head. Then it is continuously
forwarded to the next node until all the data values of the nodes are printed. This is given below.
DATA STRUCTURE AND ALGORITHM
Module I
void display()
{
struct Node* ptr;
ptr = head;
while (ptr != NULL)
{
cout<<ptr->data <<" ";
ptr = ptr->next;
}
}
In the function main(), first various values are inserted into the linked list by calling insert(). Then the
linked list is displayed. This is given below.
int main()
{
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: ";
display();
return 0;
}
Advantages of SLL
1. Theelements can beaccessed usingthe nextlink.
2. OccupieslessmemorythanDLLasithasonlyonenextfield.
DisadvantagesofSLL
1. Traversalinthebackwardsisnot possible
2. Lessefficienttoforinsertionanddeletion.
STACK
DATA STRUCTURE AND ALGORITHM
Module I
Stack is a Linear Data Structure that follows Last In First Out (LIFO) principle.
Insertion and deletion can be done at only one end of the stack called TOP of the stack.
STACKADT:
TOP pointer
It will always point to the last element inserted in the stack. For empty stack, top will be
Two fundamental operations performed on the stack are PUSH and POP.
(a) PUSH:
It is the process of inserting a new element at the Top of the stack.
For every push operation:
(b) POP:
1. Stack Overflow
An Attempt to insert an element X when the stack is Full, is said to be stack overflow.
For every Push operation, we need to check this condition.
2. Stack Underflow:
An Attempt to delete an element when the stack is empty, is said to be stack underflow.
For every Pop operation, we need to check this condition.
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. For example, we can place or remove a card or
plate from the top of the stack only. Likewise, Stack ADT allows all data operations at one end only.
At any given time, we can only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is
placed (inserted or added) last, is accessed first. In stack terminology, insertion operation is
called PUSH operation and removal operation is called POP operation.
DATA STRUCTURE AND ALGORITHM
Module I
Stack Representation
The following diagram depicts a stack and its operations −
A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack can either
be a fixed size one or it may have a sense of dynamic resizing. Here, we are going to implement stack
using arrays, which makes it a fixed size stack implementation.
Basic Operations
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these
basic stuffs, a stack is used for the following two primary operations −
push() − Pushing (storing) an element on the stack.
pop() − Removing (accessing) an element from the stack.
When data is PUSHed onto stack.
To use a stack efficiently, we need to check the status of stack as well. For the same
purpose, the following functionality is added to stacks −
peek() − get the top data element of the stack, without removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.
At all times, we maintain a pointer to the last PUSHed data on the stack.
As this pointer always represents the top of the stack, hence named top.
The top pointer provides top value of the stack without actually removing it.
DATA STRUCTURE AND ALGORITHM
Module I
isfull()
Algorithm of isfull() function −
end procedure
isempty()
Algorithm of isempty() function −
end procedure
Example
boolisempty(){
if(top ==-1)
returntrue;
else
returnfalse;
}
Push Operation
The process of putting a new data element onto stack is known as a Push Operation. Push operation
involves a series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point next empty space.
Step 4 − Adds data element to the stack location, where top is pointing.
Step 5 − Returns success.
DATA STRUCTURE AND ALGORITHM
Module I
If the linked list is used to implement the stack, then in step 3, we need to allocate space
dynamically.
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an
array implementation of pop() operation, the data element is not actually removed,
instead top is decremented to a lower position in the stack to point to the next value. But in
linked-list implementation, pop() actually removes data element and deallocates memory
space.
A Pop operation may involve the following steps −
Step 1 − Checks if the stack is empty.
DATA STRUCTURE AND ALGORITHM
Module I
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
if stack is empty
returnnull
endif
data← stack[top]
top← top -1
return data
end procedure
if(!isempty()){
data= stack[top];
top= top -1;
return data;
}else{
printf("Could not retrieve data, Stack is empty.\n");
}}
DATA STRUCTURE AND ALGORITHM
Module I
Queue
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both
its ends. One end is always used to insert data (enqueue) and the other is used to remove data
(dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be
accessed first.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits
first. More real-world examples can be seen as queues at the ticket windows and bus-stops.
Queue Representation
As we now understand that in queue, we access both ends for different reasons. The following diagram
given below tries to explain queue representation as data structure −
As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers and Structures. For
the sake of simplicity, we shall implement queues using one-dimensional array.
Basic Operations
Queue operations may involve initializing or defining the queue, utilizing it, and then completely
erasing it from the memory. Here we shall try to understand the basic operations associated with
queues −
enqueue() − add (store) an item to the queue.
dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient.
DATA STRUCTURE AND ALGORITHM
Module I
These are −
peek() − Gets the element at the front of the queue without removing it.
isfull() − Checks if the queue is full.
isempty() − Checks if the queue is empty.
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing
(or storing) data in the queue we take help of rear pointer.
Algorithm
begin procedure peek
return queue[front]
end procedure
isempty()
Algorithm of isempty() function −
Algorithm
begin procedure isempty
if front is less than MIN OR front is greater than rear
return true
else
return false
endif
end procedure
If the value of front is less than MIN or 0, it tells that the queue is not yet initialized, hence
empty.
Here's the C programming code −
Example
boolisempty() {
if(front < 0 || front > rear)
return true;
else
return false;
}
Enqueue Operation
Queues maintain two data pointers, front and rear. Therefore, its operations are
comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
Step 1 − Check if the queue is full.
Step 2 − If the queue is full, produce overflow error and exit.
Step 3 − If the queue is not full, increment rear pointer to point the next empty space.
Step 4 − Add data element to the queue location, where the rear is pointing.
Step 5 − return success.
DATA STRUCTURE AND ALGORITHM
Module I
Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseen
situations.
Algorithm for enqueue operation
procedureenqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Implementation of enqueue() in C programming language −
Example
intenqueue(int data)
if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
DATA STRUCTURE AND ALGORITHM
Module I
Dequeue Operation
Accessing data from the queue is a process of two tasks − access the data where front is pointing and
remove the data after access. The following steps are taken to perform dequeue operation −
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
For example –
Let’s understand infix, prefix, and postfix expression with a clear example
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.
In postfix expression, an operator is written after its operands. This notation is also known
as “Reverse Polish notation”.
Eg: The above expression can be written in the postfix form as A B +
The postfix expression as the name suggests has the operator placed right after the two
operands.
It is of the form <operand><operand><operator>
In the infix expressions, it is difficult to keep track of the operator precedence whereas here the
postfix expression itself determines the precedence of operators (which is done by the
placement of operators)i.e the operator which occurs first operates on the operand.
E.g. PQ-C/, here – operation is done on P and Q and then / is applied on C and the previous
result.
A postfix expression is a parenthesis-free expression. For evaluation, we evaluate it from left to
right.
DATA STRUCTURE AND ALGORITHM
Module I
What is prefix expression?
The prefix expression as the name suggests has the operator placed before the operand is
specified.
It is of the form <operator><operand><operand>.
It works entirely in the same manner as the postfix expression.
While evaluating a prefix expression, the operators are applied to the operands immediately on
the right of the operator.
For evaluation, we evaluate it from left to right. Prefix expressions are also called polish
notation.
We can convert the infix expression to prefix as well as postfix and vice versa.
Now we need to calculate the value of these arithmetic operations by using a stack.
The procedure for getting the result is:
For example –
Polynomial Manipulation
Linked lists can be used to represent polynomials and the different operations that can be
performed on them
Polynomial Representation
Addition of Polynomials:
To add two polynomials, we need to scan them once.
If we find terms with the same exponent in the two polynomials,
Then we add the coefficients; otherwise, we copy the term of larger exponent into the sum
and go on. When we reach at the end of one of the polynomial, then remaining part of the
other is copied into the sum.
To add two polynomials, follow the following steps:
Read two polynomials.
Add them.
If the polynomial is 2x2+3x+4, then it is written in the form of 2x2+3x1+4x0 and represented it using a
linked list. In the diagram, AON means "address of next node".
POLYNOMIAL ADDITION