DSA_Lecture Notes - Part 1
DSA_Lecture Notes - Part 1
cout
This method is used to print variable / string / character. Syntax:
cout<< variable / charcter / string;
Functions in C++
A function is a block of code that performs a specific task. It has a name and it is reusable i.e. it can
be executed from as many different parts as required. It also optionally returns a value to the calling
function.
A complex problem may be decomposed into a small or easily manageable parts or modules called
functions. Functions are very useful to read, write, debug and modify complex programs They can also
be incorporated in the main program. The main() itself is a function is invoking the other functions to
perfom various tasks.
return_type function_name(argument_list)
{ statement 1;
.
.
Statements n;
}
CALL BY VALUE
In call by value, value being passed to the function is locally stored by the function parameter in stack
memory location. If you change the value of function parameter, it is changed for the current function
only. It will not change the value of variable inside the caller method.
int main()
{
int data = 3; change(data);
cout << "Value of the data is: " << data<< endl; return 0;
}
void change(int data)
{
data = 5;
}
1
Call BY REFERENCE
In call by reference, original value is modified because we pass reference (address).
Here, address of the value is passed in the function, so actual and formal arguments share the same
address space. Hence, value changed inside the function, is reflected inside as well as outside the
function.
#include<iostream> using
namespace std; void swap(int *x,
int *y)
{
int swap; swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl; cout<<"Value of y is:
"<<y<<endl;
return 0;
}
C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that have
contiguous memory location.
C++ Array Types
There are 2 types of arrays in C++ programming:
• Single Dimensional Array
• Multidimensional Array
C++ Pointers
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.
2
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and
used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many usage of pointers in C++ language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
pointer is used.
2) Arrays, Functions and Structures
Pointers in c language are widely used in arrays, functions and structures. It reduces the code and
improves the performance.
int main()
{
int number=30; int ∗ p;
p=&number;//stores the address of number variable cout<<"Address
of number variable is:"<<&number<<endl; cout<<"Address of p
variable is:"<<p<<endl; cout<<"Value of p variable is:"<<*p<<endl;
return 0;
}
delete Operator :
delete operator is used to Deallocates the dynamically allocated memory.
Since the necessity of dynamic memory is usually limited to specific moments within a program, once
it is no longer needed it should be freed so that the memory becomes available again for other requests
of dynamic memory. This is the purpose of the operator delete.
delete takes the following general form:
1. delete pointer_variable;
2. delete []pointer_variable;
#include<iostream.h>
void main()
{
3
int size,i; int *ptr;
cout<<"\n\tEnter size of Array : "; cin>>size;
ptr = new int[size];
for(i=0;i<5;i++) //Input arrray from user.
{
4
cout<<"\nEnter any number : "; cin>>ptr[i];
}
delete[] ptr;
//deallocating all the memory created by new operator
Array as an ADT
The array is a basic abstract data type that holds an ordered collection of items accessible by an integer
index. Since it's an ADT, it doesn't specify an implementation, but is almost always implemented by an
array data structure or dynamic array.
5
*The last node in the list contains NULL pointer to indicate that it is the end of the list. Conceptual
view of Singly Linked List
temp
head is the pointer variable which contains address of the first node and temp contains address of
6
new node to be inserted then sample code is
After insertion
2 4 5 6
struct Node
{
int data;
struct Node *next;
};
struct Node *head = NULL;
void insert(int value)
{
struct Node *newnode = new Node();
newnode -> data = value;
if(head==NULL)
{
newnode -> next = NULL;
head = newnode;
}
else
{
newnode -> next = head;
head = newnode;
}
}
case 2:Inserting end of the list
7
void insertatend(int value)
{
Node *newnode = new Node();
struct Node *temp = head;
newnode -> data = value;
newnode -> next = NULL;
if(head==NULL)
{
head = newnode;
return;
}
while(temp -> next!=NULL)
{
temp = temp -> next;
}
temp -> next = newnode;
};
case 3: Insert at a position
8
void insertatpos(int pos,int value){
int i;
struct Node *newnode = new Node();
newnode->data = value;
// newnode->next=NULL;
struct Node *temp = head;
for(i=1;i<pos;i++){
temp=temp->next;
}
newnode->next = temp->next;
temp->next = newnode;
}
Deletions: Removing an element from the list, without destroying the integrity of the list itself
To place an element from the list there are 3 cases :
1. Delete a node at beginning of the list
2. Delete a node at end of the list
3. Delete a node at a given position
Delete a node at beginning of the list
9
Delete a node at end of the list
A singly linked list has the disadvantage that we can only traverse it in one direction. Many
applications require searching backwards and forwards through sections of a list. A useful refinement
that can be made to the singly linked list is to create a doubly linked list.The distinction made between
the two list types is that while singly linked list have pointers going in one direction, doubly linked
list have pointer both to the next and to the previous element in the list. The main advantage of a
doubly linked list is that, they permit traversing or searching of the list in both directions.
In this linked list each node contains three fields.
• One to store data
• Remaining are self referential pointers which points to previous and next nodes in the list
prev data next
Implementation of node using structure
Method -1:
struct node
{
int data;
struct node *prev; struct
node * next;
};
Insertion
In a double linked list, the insertion operation can be performed in three ways as follows...
• Inserting At Beginning of the list
• Inserting At End of the list
• Inserting At Specific location in the list
Deletion
12
In a double linked list, the deletion operation can be performed in three ways as follows...
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node
14
Circular Linked List
In a circular linked list, we perform the following operations...
• Insertion
• Deletion
• Display
• Step 1 - Include all the header files which are used in the program.
• Step 2 - Declare all the user defined functions.
• Step 3 - Define a Node structure with two members data and next
• Step 4 - Define a Node pointer 'head' and set it to NULL.
• Step 5 - Implement the main method by displaying operations menu and make suitable function
calls in the main method to perform user selected operation.
Insertion
In a circular linked list, the insertion operation can be performed in three ways. They are as
follows.Inserting At Beginning of the list
• Inserting At End of the list
• Inserting At Specific location in the list
In a circular linked list, the deletion operation can be performed in three ways those are as follows...
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize both 'temp1'
and 'temp2' with head.
Step 4 - Check whether list is having only one node (temp1 → next == head)
Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting Empty list conditions)
Step 6 - If it is FALSE move the temp1 until it reaches to the last node. (until temp1 →
next == head )
Step 7 - Then set head = temp2 → next, temp1 → next = head and delete temp2.
16
Deleting from End of the list
We can use the following steps to delete a node from end of the circular linked list...
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.
Step 4 - Check whether list has only one Node (temp1 → next == head)
Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate from the
function. (Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node. Repeat the
same until temp1 reaches to the last node in the list. (until temp1 → next == head)
We can use the following steps to delete a specific node from the circular linked list...
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and initialize
'temp1' with head.
Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the last node.
And every time set 'temp2 = temp1' before moving the 'temp1' to its next node.
Step 5 - If it is reached to the last node then display 'Given node not found in the list! Deletion
not possible!!!'. And terminate the function.
Step 6 - If it is reached to the exact node which we want to delete, then check whether list is having
only one node (temp1 → next == head)
Step 7 - If list has only one node and that is the node to be deleted then set head = NULL and delete
temp1 (free(temp1)).
Step 8 - If list contains multiple nodes then check whether temp1 is the first node in the list (temp1
17
== head).
Step 9 - If temp1 is the first node then set temp2 = head and keep moving temp2 to its next node
until temp2 reaches to the last node. Then set head = head → next, temp2 → next = head and delete
temp1.
Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next ==
head).
Step 1 1- If temp1 is last node then set temp2 → next = head and delete temp1 (free(temp1)).
Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 → next and delete
temp1 (free(temp1)).
STACK
Stack is a linear data structure and very much useful in various applications of computer science.
Definition
A stack is an ordered collection of homogeneous data elements, where the insertion and deletion
operation takes place at one end only, called the top of the stack.
Like array and linked list, stack is also a linear data structure, but the only difference is that in case
of former two, insertion and deletion operations can take place at any position.
In a stack the last inserted element is always processed first. Accordingly, stacks are called as
Last-in-First-out (LIFO) lists. Other names used for stacks are “piles” and “push-down
lists”.
Stack is most commonly used to store local variables, parameters and return addresses when a
function is called.
18
Stack Model of Stack
The variable top always keeps track of the top most element or position.
19
STACK OPERATIONS
• PUSH: “Push” is the term used to insert an element into a stack.
• POP: “Pop” is the term used to delete an element from a stack.
Two additional terms used with stacks are “overflow” & “underflow”. Overflow occurs when we
try to push more information on a stack that it can hold. Underflow occurs when we try to pop an
item from a stack which is empty.
REPRESENTATION OF STACKS
A stack may be represented in the memory in various ways. Mainly there are two ways. They are:
1. Using one dimensional arrays(Static Implementation)
2. Using linked lists(Dynamic Implementation)
20
Top is a pointer to point the position of array upto which it is filled with the items of stack. With
this representation following two statuses can be stated:
EMPTY: Top<l FULL:
Top>=u+l-1
APPLICATIONS OF STACKS
1. Reversing elements in a list or string.
2. Recursion Implementation.
3. Memory management in operating systems.
4. Evaluation of postfix or prefix expressions.
5. Infix to postfix expression conversion.
6. Tree and Graph traversals.
7. Checking for parenthesis balancing in arithmetic expressions.
8. Used in parsing.
Arithmetic Expressions
An expression is a collection of operators and operands that represents a specific value. In above
definition,
□ Operator is a symbol (+,-,>,<,..) which performs a particular task like arithmetic or
logical or relational operation etc .,
□ Operands are the values on which the operators can perform the task.
Expression Types
Based on the operator position, expressions are divided into THREE types. They are as follows
:
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
21
Infix Expression
In infix expression, operator is used in between operands. This notation is also called as polish
notation. The general structure of an Infix expression is:
operand <operator> operand eg: A+B
Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the
Operands". This notation is also called as reverse - polish notation. The general structure of Postfix
expression is:
operand <operator> Eg:AB+
Prefix Expression
In prefix expression, operator is used before operands. We can say that "Operands follows the Operator".
The general structure of Prefix expression is:
<Operator > operand operand Ex:+AB
In 2nd and 3rdnotations, parentheses are not needed to determine the order evaluation of the operations in
any arithmetic expression.
Eg.: Infix Prefix Postfix
1. A+B*C A+{*BC} A+{BC*}
The computer usually evaluates an arithmetic expression written in infix notation in two steps.
1. It converts the expression to postfix notation and
2. It evaluates the postfix expression.
In each step, the stack is the main tool that is used to accomplish the given task.
2.5.1 Transform ing Infix Expression into Postfix Expression
In the infix expression we assume only exponentiation (^ or **), multiplication(*), division(/),
addition (+), subtraction(-) operations. In addition to the above operators and operands they may
contain left or right parenthesis. The operators three levels of priorities are:
High priority : ^ or ** Next
high priority:*,/ Lowest +,-
The following algorithm transforms the infix expression Q into the equivalent postfix
22
expression P. The algorithm uses a stack to temporarily hold operators and left parenthesis.
Step1: Push „(„ onto stack and add „)‟ to the end of Q.
Step 2: Scan Q from left to right and repeat steps 3 to 6 for each element of Q until STACK is empty.
Step 3: If an operand is encountered, add it to P.
Step 4: If a left parentheses is encountered, push it onto STACK.
Step 5: If an operator Ө is encountered, then:
a) Repeatedly pop from STACK and add to P each operator (on the top of
STACK) which has the same precedence as or higher precedence than Ө.
b) Add Ө to the STACK
[End of If Structure]
Step 6: If a right parentheses is encountered, then:
a) Repeatedly pop from STACK and add to P each operator (on the top of
STACK) until a left parentheses is encountered.
b) Remove the left parenthesis. [Do not add this to P]
Step 7: Exit.
23
(18) * (+* ABC*DEF^/G*-
(19) H (+* ABC*DEF^/G*-H
(20) ) ABC*DEF^/G*-H * +
24
QUEUE ADT
Queue is a linear data structure used in various applications of computer science. Like people stand
in a queue to get a particular service, various processes will wait in a queue for their turn to avail a
service.
Queue is a linear list in which insertions takes place at one end called the rear or tail of the
queue and deletions at the other end called as front or head of the queue.
When an element is to join the queue, it is inserted at the rear end of the queue and when an element is
to be deleted, the one at the front end of the queue is deleted automatically.
In queues always the first inserted element will be the first to be deleted. That‟s why it is also
called as FIFO – First-in First-Out data structure (or FCFS – First Come First Serve data structure)
APPLICATIONS OF QUEUE
□ CPU Scheduling (Round Robin Algorithm)
□ Printer Spooling
□ Tree & Graph Traversals
□ Palindrome Checker
□ Undo & Redo Operations in some Software‟s
OPERATIONS ON QUEUE
The queue data structure supports two operations:
Enqueue: Inserting an element into the queue is called enqueuing the queue. After the data have
been inserted into the queue, the new element becomes the rear.
Dequeue: Deleting an element from the queue is called dequeuing the queue. The data at the front of
the queue are returned to the user and removed from the queue.
IMPLEMENTATION OF QUEUES
Queues can be implemented or represented in memory in two ways:
1. Using Arrays (Static Implementation).
2. Using Linked Lists (Dynamic Implementation).
2.6.1.1 Implementation of Queue Us ing Arrays
A common method of implementing a queue data structure is to use another sequential data
structure, viz, arrays. With this representation, two pointers namely, Front and Rear are used to
indicate two ends of the queue. For insertion of next element, pointer Rear will be adjusted and for
deletion pointer Front will be adjusted.
25
However, the array implementation puts a limitation on the capacity of the queue. The number
of elements in the queue cannot exceed the maximum dimension of the one dimensional array.
Thus a queue that is accommodated in an array Q[1:n], cannot hold more than n elements.
Hence every insertion of an element into the queue has to necessarily test for a QUEUE
FULL condition before executing the insertion operation. Again, each deletion has to ensure
that it is not attempted on a queue which is already empty calling for the need to test for a
QUEUE EMPTY condition before executing the deletion operation.
26