SlideShare a Scribd company logo
1 of 26
Download to read offline
DATA STRUCTURES & ALGORITHMS
UNIT - 1
What are Data Structures?
Data structure is a storage that is used to store and organize data. It is a way of arranging data
on a computer so that it can be accessed and updated efficiently.
Depending on your requirement and project, it is important to choose the right data structure
for your project. For example, if you want to store data sequentially in the memory, then you
can go for the Array data structure.
Data structure and data types are slightly different. Data structure is the collection of data
types arranged in a specific order.
Types of Data Structure
Basically, data structures are divided into two categories:
1. Linear data structure
2. Non-linear data structure
Array Representation in Data Structure
Array:
An array defines as a finite ordered set of homogeneous elements. Finite means that there is a specific
number of elements and ordered means that the elements of the array are indexed. Homogeneous means that
all the elements of the array must be of the same type.
Array Representation:
In the Data Structure, there are two types of array representation are exists:
i. One Dimensional Array
ii. Two Dimensional Array
One Dimensional Array:
Values in a mathematical set are written as shown below :
a={5, 7, 9, 4, 6, 8}
These values refer in mathematics as follows :
a0, a1, a2
In Data Structure, these numbers are represented as follows :
a[0], a[1], a[2]
these values are stored in RAM as follows :
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Algorithm for insertion into One-dimensional array:
 Algorithm fnInsertion_1D_Array(arrData, n, k, item)
 {
 for(i=n-1;i>=k-1;i--)
 arrData[i+1]=arrData[i];
 arrData[k-1]=item;
 n=n-1;
 } // End of Algorithm
Algorithm for deletion from One-dimensional array:
 Algorithm fnDeletion_1D_Array(arrData, n, k)
 {
 item=arrData[k-1];
 for(i=k-1;i<n-1;i++)
 arrData[i]=arrData[i+1];
 n=n-1;
 return item;
 } // End of Algorithm
Algorithm for traversing One-dimensional array:
 Algorithm fnTraverse_1D_Array(arrData, n)
 {
 for(i=0;i<n;i++)
 print arrData[i];
 } //End of Algorithm
Two Dimensional Array:
These values are referred in mathematical as follows :
A0,0 A0,1 A0,2
In Data Structure, they are represented as follows :
a[0][0] a[0][1] a[0][2] and so on
DATA STRUCTURES & ALGORITHMS
UNIT - 1
It may be imagined that these values are stored in RAM as follows :
The Ordered List Abstract Data Type
We will now consider a type of list known as an ordered list. For example, if the list of integers
shown above were an ordered list (ascending order), then it could be written as 17, 26, 31, 54, 77, and 93.
Since 17 is the smallest item, it occupies the first position in the list. Likewise, since 93 is the largest, it
occupies the last position.
The structure of an ordered list is a collection of items where each item holds a relative position that is based
upon some underlying characteristic of the item. The ordering is typically either ascending or descending
and we assume that list items have a meaningful comparison operation that is already defined. Many of the
ordered list operations are the same as those of the unordered list.
 OrderedList() creates a new ordered list that is empty. It needs no parameters and returns an empty list.
 add(item) adds a new item to the list making sure that the order is preserved. It needs the item and returns
nothing. Assume the item is not already in the list.
 remove(item) removes the item from the list. It needs the item and modifies the list. Assume the item is
present in the list.
 search(item) searches for the item in the list. It needs the item and returns a boolean value.
 isEmpty() tests to see whether the list is empty. It needs no parameters and returns a boolean value.
 size() returns the number of items in the list. It needs no parameters and returns an integer.
 index(item) returns the position of item in the list. It needs the item and returns the index. Assume the item
is in the list.
 pop() removes and returns the last item in the list. It needs nothing and returns an item. Assume the list has
at least one item.
 pop(pos) removes and returns the item at position pos. It needs the position and returns the item. Assume the
item is in the list.
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.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
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.
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.
First we should learn about procedures to support stack functions −
DATA STRUCTURES & ALGORITHMS
UNIT - 1
peek()
Algorithm of peek() function −
begin procedure peek
return stack[top]
end procedure
Implementation of peek() function in C programming language −
Example
int peek() {
return stack[top];
}
isfull()
Algorithm of isfull() function −
begin procedure isfull
if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Implementation of isfull() function in C programming language −
Example
bool isfull() {
if(top == MAXSIZE)
return true;
else
return false;
}
isempty()
Algorithm of isempty() function −
begin procedure isempty
if top less than 1
return true
else
return false
endif
end procedure
Implementation of isempty() function in C programming language is slightly different. We initialize top at -
1, as the index in array starts from 0. So we check if the top is below zero or -1 to determine if the stack is
empty. Here's the code −
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Example
bool isempty() {
if(top == -1)
return true;
else
return false;
}
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.
If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically.
Algorithm for PUSH Operation
A simple algorithm for Push operation can be derived as follows −
begin procedure push: stack, data
if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure
Implementation of this algorithm in C, is very easy. See the following code −
Example
void push(int data) {
if(!isFull()) {
DATA STRUCTURES & ALGORITHMS
UNIT - 1
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.n");
}
}
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.
 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.
Algorithm for Pop Operation
A simple algorithm for Pop operation can be derived as follows −
begin procedure pop: stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Implementation of this algorithm in C, is as follows −
Example
DATA STRUCTURES & ALGORITHMS
UNIT - 1
int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.n");
}
}
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. These are −
 peek() − Gets the element at the front of the queue without removing it.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
 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.
Let's first learn about supportive functions of a queue −
peek()
This function helps to see the data at the front of the queue. The algorithm of peek() function is as follows −
Algorithm
begin procedure peek
return queue[front]
end procedure
Implementation of peek() function in C programming language −
Example
int peek() {
return queue[front];
}
isfull()
As we are using single dimension array to implement queue, we just check for the rear pointer to reach at
MAXSIZE to determine that the queue is full. In case we maintain the queue in a circular linked-list, the
algorithm will differ. Algorithm of isfull() function −
Algorithm
begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
endif
end procedure
Implementation of isfull() function in C programming language −
Example
bool isfull() {
if(rear == MAXSIZE - 1)
return true;
else
return false;
}
isempty()
Algorithm of isempty() function −
Algorithm
begin procedure isempty
DATA STRUCTURES & ALGORITHMS
UNIT - 1
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
bool isempty() {
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.
Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseen situations.
Algorithm for enqueue operation
procedure enqueue(data)
DATA STRUCTURES & ALGORITHMS
UNIT - 1
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
int enqueue(int data)
if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure
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.
Algorithm for dequeue operation
procedure dequeue
DATA STRUCTURES & ALGORITHMS
UNIT - 1
if queue is empty
return underflow
end if
data = queue[front]
front ← front + 1
return true
end procedure
Implementation of dequeue() in C programming language −
Example
int dequeue() {
if(isempty())
return 0;
int data = queue[front];
front = front + 1;
return data;
}
EVALUATION OF EXPRESSIONS
The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in
three different but equivalent notations, i.e., without changing the essence or output of an expression. These
notations are −
 Infix Notation
 Prefix (Polish) Notation
 Postfix (Reverse-Polish) Notation
These notations are named as how they use operator in expression. We shall learn the same here in this
chapter.
Infix Notation
We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is easy
for us humans to read, write, and speak in infix notation but the same does not go well with computing
devices. An algorithm to process infix notation could be difficult and costly in terms of time and space
consumption.
Prefix Notation
In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For
example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish
Notation.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Postfix Notation
This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to
the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its infix
notation a + b.
The following table briefly tries to show the difference in all three notations −
Sr.No. Infix Notation Prefix Notation Postfix Notation
1 a + b + a b a b +
2 (a + b) ∗ c ∗ + a b c a b + c ∗
3 a ∗ (b + c) ∗ a + b c a b c + ∗
4 a / b + c / d + / a b / c d a b / c d / +
5 (a + b) ∗ (c + d) ∗ + a b + c d a b + c d + ∗
6 ((a + b) ∗ c) - d - ∗ + a b c d a b + c ∗ d -
Parsing Expressions
As we have discussed, it is not a very efficient way to design an algorithm or program to parse infix
notations. Instead, these infix notations are first converted into either postfix or prefix notations and then
computed.
To parse any arithmetic expression, we need to take care of operator precedence and associativity also.
Precedence
When an operand is in between two different operators, which operator will take the operand first, is decided
by the precedence of an operator over others. For example −
As multiplication operation has precedence over addition, b * c will be evaluated first. A table of operator
precedence is provided later.
Associativity
Associativity describes the rule where operators with the same precedence appear in an expression. For
example, in expression a + b − c, both + and – have the same precedence, then which part of the expression
will be evaluated first, is determined by associativity of those operators. Here, both + and − are left
associative, so the expression will be evaluated as (a + b) − c.
Precedence and associativity determines the order of evaluation of an expression. Following is an operator
precedence and associativity table (highest to lowest) −
Sr.No. Operator Precedence Associativity
1 Exponentiation ^ Highest Right Associative
2 Multiplication ( ∗ ) & Division ( / ) Second Highest Left Associative
DATA STRUCTURES & ALGORITHMS
UNIT - 1
3 Addition ( + ) & Subtraction ( − ) Lowest Left Associative
The above table shows the default behavior of operators. At any point of time in expression evaluation, the
order can be altered by using parenthesis. For example −
In a + b*c, the expression part b*c will be evaluated first, with multiplication as precedence over addition.
We here use parenthesis for a + b to be evaluated first, like (a + b)*c.
Postfix Evaluation Algorithm
We shall now look at the algorithm on how to evaluate postfix notation −
Step 1 − scan the expression from left to right
Step 2 − if it is an operand push it to stack
Step 3 − if it is an operator pull operand from stack and perform operation
Step 4 − store the output of step 3, back to stack
Step 5 − scan the expression until all operands are consumed
Step 6 − pop the stack and perform operation
Example
Infix expression : 2 * (5 * (3 + 6)) / 5 – 2
Character Action Operand Stack Operator Stack
2 Push to the operand stack 2
* Push to the operator stack 2 *
( Push to the operator stack 2 ( *
5 Push to the operand stack 5 2 ( *
* Push to the operator stack 5 2 * ( *
( Push to the operator stack 2 1 ( * ( *
3 Push to the operand stack 3 5 2 ( * ( *
+ Push to the operator stack 3 2 1 + ( * ( *
6 Push to the operand stack 6 3 5 2 + ( * ( *
) Pop 6 and 3 5 2 + ( * ( *
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Pop + 5 2 ( * ( *
6 + 3 = 9, push to operand stack 9 5 2 ( * ( *
Pop ( 9 5 2 * ( *
) Pop 9 and 5 2 * ( *
Pop * 2 ( *
9 * 5 = 45, push to operand stack 45 2 ( *
Pop ( 45 2 *
/ Push to the operator stack 45 2 / *
5 Push to the operand stack 5 45 2 / *
– Pop 5 and 45 2 / *
Pop / 2 *
45/5 = 9, push to the operand stack 9 2 *
Pop 9 and 2 *
Pop *
9 * 2 = 18, push to operand stack 18
Push – to the operator stack 18 –
2 Push to the operand stack 2 18 –
Pop 2 and 18 –
Pop –
18 – 2 = 16, push to operand stack 16
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Example
For example, let us convert the infix expression we used into postfix for expression evaluation using stack.
Postfix expression : 2 5 3 6 + * * 15 / 2 –
Character Action Operand Stack
2 Push to the operand stack 2
5 Push to the operand stack 5 2
3 Push to the operand stack 3 5 2
6 Push to the operand stack 6 3 5 2
+ Pop 6 and 3 from the stack 5 2
6 + 3 = 9, push to operand stack 9 5 2
* Pop 9 and 5 from the stack 2
9 * 5 = 45, push to operand stack 45 2
* Pop 45 and 2 from the stack
45 * 2 = 90, push to stack 90
5 Push to stack 5 90
/ Pop 15 and 90 from the stack
90 / 5 = 18, push to stack 18
2 Push to the stack 2 18
– Pop 2 and 18 from the stack
18 – 2 = 16, push to stack 16
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Prefix expression: – / * 2 * 5 + 3 6 5 2
Reversed prefix expression: 2 5 6 3 + 5 * 2 * / –
Character Action Operand Stack
2 Push to the operand stack 2
5 Push to the operand stack 5 2
6 Push to the operand stack 6 5 2
3 Push to the operand stack 3 6 5 2
+ Pop 3 and 6 from the stack 5 2
3 + 6 = 9, push to operand stack 9 5 2
5 Push to the operand stack 5 9 5 2
* Pop 5 and 9 from the stack 5 2
5 * 9 = 45, push to operand stack 45 5 2
2 Push to operand stack 2 45 5 2
* Pop 2 and 45 from the stack 5 2
2 * 45 = 90, push to stack 90 5 2
/ Pop 90 and 5 from the stack 2
90 / 5 = 18, push to stack 18 2
– Pop 18 and 2 from the stack
18 – 2 = 16, push to stack 16
Data Structure Multiple Stack
A single stack is sometimes not sufficient to store a large amount of data. To overcome this problem, we can
use multiple stack. For this, we have used a single array having more than one stack. The array is divided for
multiple stacks.
Suppose there is an array STACK[n] divided into two stack STACK A and STACK B, where n = 10.
 STACK A expands from the left to the right, i.e., from 0th element.
 STACK B expands from the right to the left, i.e., from 10th element.
 The combined size of both STACK A and STACK B never exceeds 10.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Stacks Queues
Stacks are based on the LIFO principle,
i.e., the element inserted at the last, is the
first element to come out of the list.
Queues are based on the FIFO principle, i.e., the element
inserted at the first, is the first element to come out of the list.
Insertion and deletion in stacks takes
place only from one end of the list called
the top.
Insertion and deletion in queues takes place from the opposite
ends of the list. The insertion takes place at the rear of the list
and the deletion takes place from the front of the list.
Insert operation is called push operation. Insert operation is called enqueue operation.
Delete operation is called pop operation. Delete operation is called dequeue operation.
In stacks we maintain only one pointer to
access the list, called the top, which
always points to the last element present
in the list.
In queues we maintain two pointers to access the list. The
front pointer always points to the first element inserted in the
list and is still present, and the rear pointer always points to
the last inserted element.
Stack is used in solving problems works
on recursion.
Queue is used in solving problems having sequential
processing.
Stack does not have any types.
Queue is of three types – 1. Circular Queue 2. Priority queue
3. double-ended queue.
Can be considered as a vertical collection
visual. Can be considered as a horizontal collection visual.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
MULTIPLE QUEUE
Thus far, we have seen the demonstration of a single queue, but several practical applications in computer
science needs several queues. Multi queue is data structure in which multiple queues are maintained. This
type of data structures are utilized for process scheduling. We might use one dimensional array or
multidimensional array to illustrated a multiple queue.
Figure: Multiple queues in an array
A multi queue implementation by using a single dimensional array along m elements is illustrated in Figure
6. Each of queues contains n elements that are mapped to a liner array of m elements.
Multiple Queues
We can maintain two queues in the same array which is possible. If one grows from position 1 of the array
and the other grows from the last position queue refers to the data structure where the elements are stored
such that a new value is inserted at the rear end of the queue and deleted at the front end of the queue.
in order to maintain two queues there should be two Front and two rear of the two queues Both the queues
can grow up to any extent from 1st
position to maximum. Hence there should be one or more variable to
keep track of the total number of values stored. The overflow condition will appear. If count becomes equal
to or greater than array size and the underflow, condition from empty queue will appear if count =0
The structure for such an implementation be given as
Structure multiqueue
{
Int Front 0. Front 1;
Int Rear 0. Rear 1;
Int num;
Int count;
};
Initially when both the queues are empty then the initialization of front and queue as;
Front 0 = rear 0= -1
And for other queues
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Front 1= rear 1= 4.
So when one element comes in the first queue then front 0 and Rear 0 are initialized to 1 and when element
comes in the second queue then Front 1 and Rear 1 are initialized to 5. Then Rear are incremented by one
after every insertion & decremented by one after every deletion.
FIFO queue. A queue in which the first item added is always the first one out.
LIFO queue. A queue in which the item most recently added is always the first one out.
Priority queue. A queue in which the items are sorted so that the highest priority item is always the next
one to be extracted.
Life critical systems. Systems on which we depend for safety and which may result in death or injury if
they fail: medical monitoring industrial plant monitoring and control and aircraft control systems are
examples of life critical systems.
Real time systems. Systems in which time is a constraint. A system which must respond to some event
(e.g., the change in attitude of an aircraft caused by some atmospheric event like wind shear) within a fixed
time to maintain stability or continue correct operation (e.g. the aircraft systems must make necessary
adjustments to the control surfaces before the aircraft falls out of the sky!).
What is Linked List?
When we want to work with an unknown number of data values, we use a linked list data structure to
organize that data. The linked list is a linear data structure that contains a sequence of elements such that
each element links to its next element in the sequence. Each element in a linked list is called "Node".
A singly linked list is a type of linked list that is unidirectional, that is, it can be traversed in only one
direction from head to the last node (tail).
Each element in a linked list is called a node. A single node contains data and a pointer to the next node
which helps in maintaining the structure of the list.
The first node is called the head; it points to the first node of the list and helps us access every other element
in the list. The last node, also sometimes called the tail, points to NULL which helps us in determining when
DATA STRUCTURES & ALGORITHMS
UNIT - 1
the listen
Why Linked List?
Arrays can be used to store linear data of similar types, but arrays have the following limitations.
 The size of the arrays is fixed: So we must know the upper limit on the number of elements in
advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage.
 Insertion of a new element / Deletion of a existing element in an array of elements is
expensive: The room has to be created for the new elements and to create room existing elements have
to be shifted but in Linked list if we have the head node then we can traverse to any node through it
and insert new node at the required position.
For example, in a system, if we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040].
And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the
elements after 1000 (excluding 1000).
Deletion is also expensive with arrays until unless some special techniques are used. For example, to
delete 1010 in id[], everything after 1010 has to be moved due to this so much work is being done which
affects the efficiency of the code.
Operations on Single Linked List
The following operations are performed on a Single Linked List
 Insertion
 Deletion
 Display
Before we implement actual operations, first we need to set up an empty list. First, perform the following
steps before implementing actual operations.
 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.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Insertion
In a single linked list, the insertion operation can be performed in three ways. They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the single linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then, set newNode→next = NULL and head = newNode.
 Step 4 - If it is Not Empty then, set newNode→next = head and head = newNode.
Inserting At End of the list
We can use the following steps to insert a new node at end of the single linked list...
 Step 1 - Create a newNode with given value and newNode → next as NULL.
 Step 2 - Check whether list is Empty (head == NULL).
 Step 3 - If it is Empty then, set head = newNode.
 Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list (until temp
→ next is equal to NULL).
 Step 6 - Set temp → next = newNode.
Inserting At Specific location in the list (After a Node)
We can use the following steps to insert a new node after a node in the single linked list...
 Step 1 - Create a newNode with given value.
 Step 2 - Check whether list is Empty (head == NULL)
 Step 3 - If it is Empty then, set newNode → next = NULL and head = newNode.
 Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
 Step 5 - Keep moving the temp to its next node until it reaches to the node after which we want to
insert the newNode (until temp1 → data is equal to location, here location is the node value after
which we want to insert the newNode).
 Step 6 - Every time check whether temp is reached to last node or not. If it is reached to last node
then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate the
function. Otherwise move the temp to next node.
 Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp → next = newNode'
Deletion
In a single linked list, the deletion operation can be performed in three ways. They are as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the single linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 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 a Node pointer 'temp' and initialize with head.
 Step 4 - Check whether list is having only one node (temp → next == NULL)
 Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list conditions)
 Step 6 - If it is FALSE then set head = temp → next, and delete temp.
Deleting from End of the list
We can use the following steps to delete a node from end of the single linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 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 == NULL)
 Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate 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 it reaches to the last node in the list. (until temp1 → next == NULL)
 Step 7 - Finally, Set temp2 → next = NULL and delete temp1.
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the single linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 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 or not
 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
== head).
 Step 9 - If temp1 is the first node then move the head to the next node (head = head → next) and
delete temp1.
 Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next ==
NULL).
 Step 11 - If temp1 is last node then set temp2 → next = NULL and delete temp1 (free(temp1)).
DATA STRUCTURES & ALGORITHMS
UNIT - 1
 Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 → next and
delete temp1 (free(temp1)).
Displaying a Single Linked List
We can use the following steps to display the elements of a single linked list...
 Step 1 - Check whether list is Empty (head == NULL)
 Step 2 - If it is Empty then, display 'List is Empty!!!' and terminate the function.
 Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
 Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last node
 Step 5 - Finally display temp → data with arrow pointing to NULL (temp → data ---> NULL).
POLYNOMIAL ADDITION
Given two polynomial numbers represented by a linked list. Write a function that add these lists
means add the coefficients that have same variable powers.
Example:
Input:
1st number = 5x2 + 4x1 + 2x0
2nd number = -5x1 - 5x0
Output:
5x2-1x1-3x0
Input:
1st number = 5x3 + 4x2 + 2x0
2nd number = 5x^1 - 5x^0
Output:
5x3 + 4x2 + 5x1 - 3x0
Addition of polynomials can be solved in two methods.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Algorithm
Input − Polynomial p1 and p2 represented as a linked list.
Step 1: loop around all values of linked list and follow step 2& 3.
Step 2: if the value of a node’s exponent is greater copy this node to result node and head towards the next
node.
Step 3: if the values of both node’s exponent is same add the coefficients and then copy the added value with
node to the result.
Step 4: Print the resultant node.
(i) By arranging the like terms together and then add.
For example: 1. Add: 5x + 3y, 4x – 4y + z and -3x + 5y + 2z
First we need to write in the addition form. Thus, the required addition
= (5x + 3y) + (4x – 4y + z) + (-3x + 5y + 2z)
= 5x + 3y + 4x – 4y + z - 3x + 5y + 2z
Now we need to arrange all the like terms and then all the like terms are added.
5x + 4x - 3x + 3y – 4y + 5y + z + 2z
= 6x + 4y + 3z
2. Add: 3a2
+ ab – b2
, -a2
+ 2ab + 3b2
and 3a2
– 10ab + 4b2
First we need to write in the addition form. Thus, the required addition
= (3a2 + ab – b2) + (-a2 + 2ab + 3b2) + (3a2 – 10ab + 4b2)
= 3a2 + ab – b2 - a2 + 2ab + 3b2 + 3a2 – 10ab + 4b2 Here, we need to arrange the like terms and then add
= 3a2 - a2 + 3a2 + ab + 2ab – 10ab – b2 + 3b2 + 4b2
= 5a2 – 7ab + 6b2
By arranging expressions in lines so that the like terms with their signs are one below the other i.e. like
terms are in same vertical column and then add thedifferent groups of like terms.
For example:
1. Add: 7a + 5b, 6a – 6b + 3c and -5a + 7b + 4c
First we will arrange the three expressions one below the other, placing the like terms in the same
column.
DATA STRUCTURES & ALGORITHMS
UNIT - 1
Now the like terms are added by adding their coefficients with their signs.
Therefore, adding 7a + 5b, 6a – 6b + 3c and -5a + 7b + 4c is 8a + 6b + 7c.
2. Add: 3x3
– 5x2
+ 8x + 10, 15x3
– 6x – 23, 9x2
– 4x + 15 and -8x3
+ 2x2
– 7x.
First we will arrange the like terms in the vertical column and then the like terms are added by
adding their coefficients with their signs.
Therefore, adding 3x3 – 5x2 + 8x + 10, 15x3 – 6x – 23, 9x2 – 4x + 15 and - 8x3 + 2x2 – 7x is 10x3
+ 6x2 – 9x + 2.
Thus, we have learnt how to solve addition of polynomials in both the methods.

More Related Content

What's hot

Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structureMeherul1234
 
Queue implementation
Queue implementationQueue implementation
Queue implementationRajendran
 
File organization 1
File organization 1File organization 1
File organization 1Rupali Rana
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure pptNalinNishant3
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structurekalyanineve
 
Red black tree
Red black treeRed black tree
Red black treeRajendran
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applicationsJsaddam Hussain
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02Krish_ver2
 
Terminology of tree
Terminology of treeTerminology of tree
Terminology of treeRacksaviR
 
15. Transactions in DBMS
15. Transactions in DBMS15. Transactions in DBMS
15. Transactions in DBMSkoolkampus
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm03446940736
 
Hashing In Data Structure
Hashing In Data Structure Hashing In Data Structure
Hashing In Data Structure Meghaj Mallick
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structuresDurgaDeviCbit
 

What's hot (20)

Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structure
 
Queue implementation
Queue implementationQueue implementation
Queue implementation
 
Dfs
DfsDfs
Dfs
 
File organization 1
File organization 1File organization 1
File organization 1
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Unit 1 introduction to data structure
Unit 1   introduction to data structureUnit 1   introduction to data structure
Unit 1 introduction to data structure
 
Red black tree
Red black treeRed black tree
Red black tree
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Linked list implementation of Queue
Linked list implementation of QueueLinked list implementation of Queue
Linked list implementation of Queue
 
2.5 bfs & dfs 02
2.5 bfs & dfs 022.5 bfs & dfs 02
2.5 bfs & dfs 02
 
Multi ways trees
Multi ways treesMulti ways trees
Multi ways trees
 
linear probing
linear probinglinear probing
linear probing
 
Terminology of tree
Terminology of treeTerminology of tree
Terminology of tree
 
15. Transactions in DBMS
15. Transactions in DBMS15. Transactions in DBMS
15. Transactions in DBMS
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm
 
Hashing In Data Structure
Hashing In Data Structure Hashing In Data Structure
Hashing In Data Structure
 
Single linked list
Single linked listSingle linked list
Single linked list
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Acid properties
Acid propertiesAcid properties
Acid properties
 

Similar to DS UNIT 1.pdf

What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueBalwant Gorad
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبياناتRafal Edward
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdfTobyWtf
 
Ds
DsDs
DsAcad
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptxDwijBaxi
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.pptSeethaDinesh
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptxselemonGamo
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptxskilljiolms
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptxSonaPathak4
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.pptsoniya555961
 

Similar to DS UNIT 1.pdf (20)

What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
هياكلبيانات
هياكلبياناتهياكلبيانات
هياكلبيانات
 
Stack
StackStack
Stack
 
Stacks-and-Queues.pdf
Stacks-and-Queues.pdfStacks-and-Queues.pdf
Stacks-and-Queues.pdf
 
Ds
DsDs
Ds
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx01-Introduction of DSA-1.pptx
01-Introduction of DSA-1.pptx
 
unit 5 stack & queue.ppt
unit 5 stack & queue.pptunit 5 stack & queue.ppt
unit 5 stack & queue.ppt
 
chapter three ppt.pptx
chapter three ppt.pptxchapter three ppt.pptx
chapter three ppt.pptx
 
VCE Unit 03vv.pptx
VCE Unit 03vv.pptxVCE Unit 03vv.pptx
VCE Unit 03vv.pptx
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Module 2 ppt.pptx
Module 2 ppt.pptxModule 2 ppt.pptx
Module 2 ppt.pptx
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
 
04 stacks
04 stacks04 stacks
04 stacks
 
01-intro_stacks.ppt
01-intro_stacks.ppt01-intro_stacks.ppt
01-intro_stacks.ppt
 
Lecture5
Lecture5Lecture5
Lecture5
 

More from SeethaDinesh

Input Devices.pptx
Input Devices.pptxInput Devices.pptx
Input Devices.pptxSeethaDinesh
 
Generations of Computers.ppt
Generations of Computers.pptGenerations of Computers.ppt
Generations of Computers.pptSeethaDinesh
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.pptSeethaDinesh
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.pptSeethaDinesh
 
PROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxPROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxSeethaDinesh
 
Cloud Computing Basics.pptx
Cloud Computing Basics.pptxCloud Computing Basics.pptx
Cloud Computing Basics.pptxSeethaDinesh
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptSeethaDinesh
 
Structure and Union.ppt
Structure and Union.pptStructure and Union.ppt
Structure and Union.pptSeethaDinesh
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docxSeethaDinesh
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptSeethaDinesh
 
NME WPI UNIt 3.pptx
NME WPI UNIt 3.pptxNME WPI UNIt 3.pptx
NME WPI UNIt 3.pptxSeethaDinesh
 
NME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdfNME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdfSeethaDinesh
 
graphtraversals.pdf
graphtraversals.pdfgraphtraversals.pdf
graphtraversals.pdfSeethaDinesh
 

More from SeethaDinesh (20)

Input Devices.pptx
Input Devices.pptxInput Devices.pptx
Input Devices.pptx
 
Generations of Computers.ppt
Generations of Computers.pptGenerations of Computers.ppt
Generations of Computers.ppt
 
Inheritance in java.ppt
Inheritance in java.pptInheritance in java.ppt
Inheritance in java.ppt
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.ppt
 
PROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptxPROGRAMMING IN JAVA unit 1.pptx
PROGRAMMING IN JAVA unit 1.pptx
 
Cloud Computing Basics.pptx
Cloud Computing Basics.pptxCloud Computing Basics.pptx
Cloud Computing Basics.pptx
 
Greedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.pptGreedy_Backtracking graph coloring.ppt
Greedy_Backtracking graph coloring.ppt
 
Structure and Union.ppt
Structure and Union.pptStructure and Union.ppt
Structure and Union.ppt
 
Shortest Path Problem.docx
Shortest Path Problem.docxShortest Path Problem.docx
Shortest Path Problem.docx
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
NME UNIT II.ppt
NME UNIT II.pptNME UNIT II.ppt
NME UNIT II.ppt
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
chapter 1.pptx
chapter 1.pptxchapter 1.pptx
chapter 1.pptx
 
DW unit 3.pptx
DW unit 3.pptxDW unit 3.pptx
DW unit 3.pptx
 
DW unit 2.pdf
DW unit 2.pdfDW unit 2.pdf
DW unit 2.pdf
 
DW Unit 1.pdf
DW Unit 1.pdfDW Unit 1.pdf
DW Unit 1.pdf
 
NME WPI UNIt 3.pptx
NME WPI UNIt 3.pptxNME WPI UNIt 3.pptx
NME WPI UNIt 3.pptx
 
NME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdfNME UNIT I & II MATERIAL.pdf
NME UNIT I & II MATERIAL.pdf
 
graphtraversals.pdf
graphtraversals.pdfgraphtraversals.pdf
graphtraversals.pdf
 

Recently uploaded

Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptxAmazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptxAbdelrhman abooda
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdfHuman37
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDRafezzaman
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceSapana Sha
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...Pooja Nehwal
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Jack DiGiovanna
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...soniya singh
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxFurkanTasci3
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home ServiceSapana Sha
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130Suhani Kapoor
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPramod Kumar Srivastava
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...ThinkInnovation
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfgstagge
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsappssapnasaifi408
 

Recently uploaded (20)

Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptxAmazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
Amazon TQM (2) Amazon TQM (2)Amazon TQM (2).pptx
 
20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf20240419 - Measurecamp Amsterdam - SAM.pdf
20240419 - Measurecamp Amsterdam - SAM.pdf
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
 
Call Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts ServiceCall Girls In Dwarka 9654467111 Escorts Service
Call Girls In Dwarka 9654467111 Escorts Service
 
Decoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in ActionDecoding Loan Approval: Predictive Modeling in Action
Decoding Loan Approval: Predictive Modeling in Action
 
E-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptxE-Commerce Order PredictionShraddha Kamble.pptx
E-Commerce Order PredictionShraddha Kamble.pptx
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
Building on a FAIRly Strong Foundation to Connect Academic Research to Transl...
 
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
 
Data Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptxData Science Jobs and Salaries Analysis.pptx
Data Science Jobs and Salaries Analysis.pptx
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service9654467111 Call Girls In Munirka Hotel And Home Service
9654467111 Call Girls In Munirka Hotel And Home Service
 
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
VIP Call Girls Service Miyapur Hyderabad Call +91-8250192130
 
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptxPKS-TGC-1084-630 - Stage 1 Proposal.pptx
PKS-TGC-1084-630 - Stage 1 Proposal.pptx
 
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
Predictive Analysis - Using Insight-informed Data to Determine Factors Drivin...
 
RadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdfRadioAdProWritingCinderellabyButleri.pdf
RadioAdProWritingCinderellabyButleri.pdf
 
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /WhatsappsBeautiful Sapna Vip  Call Girls Hauz Khas 9711199012 Call /Whatsapps
Beautiful Sapna Vip Call Girls Hauz Khas 9711199012 Call /Whatsapps
 

DS UNIT 1.pdf

  • 1. DATA STRUCTURES & ALGORITHMS UNIT - 1 What are Data Structures? Data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. Depending on your requirement and project, it is important to choose the right data structure for your project. For example, if you want to store data sequentially in the memory, then you can go for the Array data structure. Data structure and data types are slightly different. Data structure is the collection of data types arranged in a specific order. Types of Data Structure Basically, data structures are divided into two categories: 1. Linear data structure 2. Non-linear data structure Array Representation in Data Structure Array: An array defines as a finite ordered set of homogeneous elements. Finite means that there is a specific number of elements and ordered means that the elements of the array are indexed. Homogeneous means that all the elements of the array must be of the same type. Array Representation: In the Data Structure, there are two types of array representation are exists: i. One Dimensional Array ii. Two Dimensional Array One Dimensional Array: Values in a mathematical set are written as shown below : a={5, 7, 9, 4, 6, 8} These values refer in mathematics as follows : a0, a1, a2 In Data Structure, these numbers are represented as follows : a[0], a[1], a[2] these values are stored in RAM as follows :
  • 2. DATA STRUCTURES & ALGORITHMS UNIT - 1 Algorithm for insertion into One-dimensional array:  Algorithm fnInsertion_1D_Array(arrData, n, k, item)  {  for(i=n-1;i>=k-1;i--)  arrData[i+1]=arrData[i];  arrData[k-1]=item;  n=n-1;  } // End of Algorithm Algorithm for deletion from One-dimensional array:  Algorithm fnDeletion_1D_Array(arrData, n, k)  {  item=arrData[k-1];  for(i=k-1;i<n-1;i++)  arrData[i]=arrData[i+1];  n=n-1;  return item;  } // End of Algorithm Algorithm for traversing One-dimensional array:  Algorithm fnTraverse_1D_Array(arrData, n)  {  for(i=0;i<n;i++)  print arrData[i];  } //End of Algorithm Two Dimensional Array: These values are referred in mathematical as follows : A0,0 A0,1 A0,2 In Data Structure, they are represented as follows : a[0][0] a[0][1] a[0][2] and so on
  • 3. DATA STRUCTURES & ALGORITHMS UNIT - 1 It may be imagined that these values are stored in RAM as follows : The Ordered List Abstract Data Type We will now consider a type of list known as an ordered list. For example, if the list of integers shown above were an ordered list (ascending order), then it could be written as 17, 26, 31, 54, 77, and 93. Since 17 is the smallest item, it occupies the first position in the list. Likewise, since 93 is the largest, it occupies the last position. The structure of an ordered list is a collection of items where each item holds a relative position that is based upon some underlying characteristic of the item. The ordering is typically either ascending or descending and we assume that list items have a meaningful comparison operation that is already defined. Many of the ordered list operations are the same as those of the unordered list.  OrderedList() creates a new ordered list that is empty. It needs no parameters and returns an empty list.  add(item) adds a new item to the list making sure that the order is preserved. It needs the item and returns nothing. Assume the item is not already in the list.  remove(item) removes the item from the list. It needs the item and modifies the list. Assume the item is present in the list.  search(item) searches for the item in the list. It needs the item and returns a boolean value.  isEmpty() tests to see whether the list is empty. It needs no parameters and returns a boolean value.  size() returns the number of items in the list. It needs no parameters and returns an integer.  index(item) returns the position of item in the list. It needs the item and returns the index. Assume the item is in the list.  pop() removes and returns the last item in the list. It needs nothing and returns an item. Assume the list has at least one item.  pop(pos) removes and returns the item at position pos. It needs the position and returns the item. Assume the item is in the list. 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.
  • 4. DATA STRUCTURES & ALGORITHMS UNIT - 1 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. 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. First we should learn about procedures to support stack functions −
  • 5. DATA STRUCTURES & ALGORITHMS UNIT - 1 peek() Algorithm of peek() function − begin procedure peek return stack[top] end procedure Implementation of peek() function in C programming language − Example int peek() { return stack[top]; } isfull() Algorithm of isfull() function − begin procedure isfull if top equals to MAXSIZE return true else return false endif end procedure Implementation of isfull() function in C programming language − Example bool isfull() { if(top == MAXSIZE) return true; else return false; } isempty() Algorithm of isempty() function − begin procedure isempty if top less than 1 return true else return false endif end procedure Implementation of isempty() function in C programming language is slightly different. We initialize top at - 1, as the index in array starts from 0. So we check if the top is below zero or -1 to determine if the stack is empty. Here's the code −
  • 6. DATA STRUCTURES & ALGORITHMS UNIT - 1 Example bool isempty() { if(top == -1) return true; else return false; } 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. If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically. Algorithm for PUSH Operation A simple algorithm for Push operation can be derived as follows − begin procedure push: stack, data if stack is full return null endif top ← top + 1 stack[top] ← data end procedure Implementation of this algorithm in C, is very easy. See the following code − Example void push(int data) { if(!isFull()) {
  • 7. DATA STRUCTURES & ALGORITHMS UNIT - 1 top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.n"); } } 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.  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. Algorithm for Pop Operation A simple algorithm for Pop operation can be derived as follows − begin procedure pop: stack if stack is empty return null endif data ← stack[top] top ← top - 1 return data end procedure Implementation of this algorithm in C, is as follows − Example
  • 8. DATA STRUCTURES & ALGORITHMS UNIT - 1 int pop(int data) { if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.n"); } } 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. These are −  peek() − Gets the element at the front of the queue without removing it.
  • 9. DATA STRUCTURES & ALGORITHMS UNIT - 1  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. Let's first learn about supportive functions of a queue − peek() This function helps to see the data at the front of the queue. The algorithm of peek() function is as follows − Algorithm begin procedure peek return queue[front] end procedure Implementation of peek() function in C programming language − Example int peek() { return queue[front]; } isfull() As we are using single dimension array to implement queue, we just check for the rear pointer to reach at MAXSIZE to determine that the queue is full. In case we maintain the queue in a circular linked-list, the algorithm will differ. Algorithm of isfull() function − Algorithm begin procedure isfull if rear equals to MAXSIZE return true else return false endif end procedure Implementation of isfull() function in C programming language − Example bool isfull() { if(rear == MAXSIZE - 1) return true; else return false; } isempty() Algorithm of isempty() function − Algorithm begin procedure isempty
  • 10. DATA STRUCTURES & ALGORITHMS UNIT - 1 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 bool isempty() { 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. Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseen situations. Algorithm for enqueue operation procedure enqueue(data)
  • 11. DATA STRUCTURES & ALGORITHMS UNIT - 1 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 int enqueue(int data) if(isfull()) return 0; rear = rear + 1; queue[rear] = data; return 1; end procedure 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. Algorithm for dequeue operation procedure dequeue
  • 12. DATA STRUCTURES & ALGORITHMS UNIT - 1 if queue is empty return underflow end if data = queue[front] front ← front + 1 return true end procedure Implementation of dequeue() in C programming language − Example int dequeue() { if(isempty()) return 0; int data = queue[front]; front = front + 1; return data; } EVALUATION OF EXPRESSIONS The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different but equivalent notations, i.e., without changing the essence or output of an expression. These notations are −  Infix Notation  Prefix (Polish) Notation  Postfix (Reverse-Polish) Notation These notations are named as how they use operator in expression. We shall learn the same here in this chapter. Infix Notation We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is easy for us humans to read, write, and speak in infix notation but the same does not go well with computing devices. An algorithm to process infix notation could be difficult and costly in terms of time and space consumption. Prefix Notation In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation.
  • 13. DATA STRUCTURES & ALGORITHMS UNIT - 1 Postfix Notation This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its infix notation a + b. The following table briefly tries to show the difference in all three notations − Sr.No. Infix Notation Prefix Notation Postfix Notation 1 a + b + a b a b + 2 (a + b) ∗ c ∗ + a b c a b + c ∗ 3 a ∗ (b + c) ∗ a + b c a b c + ∗ 4 a / b + c / d + / a b / c d a b / c d / + 5 (a + b) ∗ (c + d) ∗ + a b + c d a b + c d + ∗ 6 ((a + b) ∗ c) - d - ∗ + a b c d a b + c ∗ d - Parsing Expressions As we have discussed, it is not a very efficient way to design an algorithm or program to parse infix notations. Instead, these infix notations are first converted into either postfix or prefix notations and then computed. To parse any arithmetic expression, we need to take care of operator precedence and associativity also. Precedence When an operand is in between two different operators, which operator will take the operand first, is decided by the precedence of an operator over others. For example − As multiplication operation has precedence over addition, b * c will be evaluated first. A table of operator precedence is provided later. Associativity Associativity describes the rule where operators with the same precedence appear in an expression. For example, in expression a + b − c, both + and – have the same precedence, then which part of the expression will be evaluated first, is determined by associativity of those operators. Here, both + and − are left associative, so the expression will be evaluated as (a + b) − c. Precedence and associativity determines the order of evaluation of an expression. Following is an operator precedence and associativity table (highest to lowest) − Sr.No. Operator Precedence Associativity 1 Exponentiation ^ Highest Right Associative 2 Multiplication ( ∗ ) & Division ( / ) Second Highest Left Associative
  • 14. DATA STRUCTURES & ALGORITHMS UNIT - 1 3 Addition ( + ) & Subtraction ( − ) Lowest Left Associative The above table shows the default behavior of operators. At any point of time in expression evaluation, the order can be altered by using parenthesis. For example − In a + b*c, the expression part b*c will be evaluated first, with multiplication as precedence over addition. We here use parenthesis for a + b to be evaluated first, like (a + b)*c. Postfix Evaluation Algorithm We shall now look at the algorithm on how to evaluate postfix notation − Step 1 − scan the expression from left to right Step 2 − if it is an operand push it to stack Step 3 − if it is an operator pull operand from stack and perform operation Step 4 − store the output of step 3, back to stack Step 5 − scan the expression until all operands are consumed Step 6 − pop the stack and perform operation Example Infix expression : 2 * (5 * (3 + 6)) / 5 – 2 Character Action Operand Stack Operator Stack 2 Push to the operand stack 2 * Push to the operator stack 2 * ( Push to the operator stack 2 ( * 5 Push to the operand stack 5 2 ( * * Push to the operator stack 5 2 * ( * ( Push to the operator stack 2 1 ( * ( * 3 Push to the operand stack 3 5 2 ( * ( * + Push to the operator stack 3 2 1 + ( * ( * 6 Push to the operand stack 6 3 5 2 + ( * ( * ) Pop 6 and 3 5 2 + ( * ( *
  • 15. DATA STRUCTURES & ALGORITHMS UNIT - 1 Pop + 5 2 ( * ( * 6 + 3 = 9, push to operand stack 9 5 2 ( * ( * Pop ( 9 5 2 * ( * ) Pop 9 and 5 2 * ( * Pop * 2 ( * 9 * 5 = 45, push to operand stack 45 2 ( * Pop ( 45 2 * / Push to the operator stack 45 2 / * 5 Push to the operand stack 5 45 2 / * – Pop 5 and 45 2 / * Pop / 2 * 45/5 = 9, push to the operand stack 9 2 * Pop 9 and 2 * Pop * 9 * 2 = 18, push to operand stack 18 Push – to the operator stack 18 – 2 Push to the operand stack 2 18 – Pop 2 and 18 – Pop – 18 – 2 = 16, push to operand stack 16
  • 16. DATA STRUCTURES & ALGORITHMS UNIT - 1 Example For example, let us convert the infix expression we used into postfix for expression evaluation using stack. Postfix expression : 2 5 3 6 + * * 15 / 2 – Character Action Operand Stack 2 Push to the operand stack 2 5 Push to the operand stack 5 2 3 Push to the operand stack 3 5 2 6 Push to the operand stack 6 3 5 2 + Pop 6 and 3 from the stack 5 2 6 + 3 = 9, push to operand stack 9 5 2 * Pop 9 and 5 from the stack 2 9 * 5 = 45, push to operand stack 45 2 * Pop 45 and 2 from the stack 45 * 2 = 90, push to stack 90 5 Push to stack 5 90 / Pop 15 and 90 from the stack 90 / 5 = 18, push to stack 18 2 Push to the stack 2 18 – Pop 2 and 18 from the stack 18 – 2 = 16, push to stack 16
  • 17. DATA STRUCTURES & ALGORITHMS UNIT - 1 Prefix expression: – / * 2 * 5 + 3 6 5 2 Reversed prefix expression: 2 5 6 3 + 5 * 2 * / – Character Action Operand Stack 2 Push to the operand stack 2 5 Push to the operand stack 5 2 6 Push to the operand stack 6 5 2 3 Push to the operand stack 3 6 5 2 + Pop 3 and 6 from the stack 5 2 3 + 6 = 9, push to operand stack 9 5 2 5 Push to the operand stack 5 9 5 2 * Pop 5 and 9 from the stack 5 2 5 * 9 = 45, push to operand stack 45 5 2 2 Push to operand stack 2 45 5 2 * Pop 2 and 45 from the stack 5 2 2 * 45 = 90, push to stack 90 5 2 / Pop 90 and 5 from the stack 2 90 / 5 = 18, push to stack 18 2 – Pop 18 and 2 from the stack 18 – 2 = 16, push to stack 16 Data Structure Multiple Stack A single stack is sometimes not sufficient to store a large amount of data. To overcome this problem, we can use multiple stack. For this, we have used a single array having more than one stack. The array is divided for multiple stacks. Suppose there is an array STACK[n] divided into two stack STACK A and STACK B, where n = 10.  STACK A expands from the left to the right, i.e., from 0th element.  STACK B expands from the right to the left, i.e., from 10th element.  The combined size of both STACK A and STACK B never exceeds 10.
  • 18. DATA STRUCTURES & ALGORITHMS UNIT - 1 Stacks Queues Stacks are based on the LIFO principle, i.e., the element inserted at the last, is the first element to come out of the list. Queues are based on the FIFO principle, i.e., the element inserted at the first, is the first element to come out of the list. Insertion and deletion in stacks takes place only from one end of the list called the top. Insertion and deletion in queues takes place from the opposite ends of the list. The insertion takes place at the rear of the list and the deletion takes place from the front of the list. Insert operation is called push operation. Insert operation is called enqueue operation. Delete operation is called pop operation. Delete operation is called dequeue operation. In stacks we maintain only one pointer to access the list, called the top, which always points to the last element present in the list. In queues we maintain two pointers to access the list. The front pointer always points to the first element inserted in the list and is still present, and the rear pointer always points to the last inserted element. Stack is used in solving problems works on recursion. Queue is used in solving problems having sequential processing. Stack does not have any types. Queue is of three types – 1. Circular Queue 2. Priority queue 3. double-ended queue. Can be considered as a vertical collection visual. Can be considered as a horizontal collection visual.
  • 19. DATA STRUCTURES & ALGORITHMS UNIT - 1 MULTIPLE QUEUE Thus far, we have seen the demonstration of a single queue, but several practical applications in computer science needs several queues. Multi queue is data structure in which multiple queues are maintained. This type of data structures are utilized for process scheduling. We might use one dimensional array or multidimensional array to illustrated a multiple queue. Figure: Multiple queues in an array A multi queue implementation by using a single dimensional array along m elements is illustrated in Figure 6. Each of queues contains n elements that are mapped to a liner array of m elements. Multiple Queues We can maintain two queues in the same array which is possible. If one grows from position 1 of the array and the other grows from the last position queue refers to the data structure where the elements are stored such that a new value is inserted at the rear end of the queue and deleted at the front end of the queue. in order to maintain two queues there should be two Front and two rear of the two queues Both the queues can grow up to any extent from 1st position to maximum. Hence there should be one or more variable to keep track of the total number of values stored. The overflow condition will appear. If count becomes equal to or greater than array size and the underflow, condition from empty queue will appear if count =0 The structure for such an implementation be given as Structure multiqueue { Int Front 0. Front 1; Int Rear 0. Rear 1; Int num; Int count; }; Initially when both the queues are empty then the initialization of front and queue as; Front 0 = rear 0= -1 And for other queues
  • 20. DATA STRUCTURES & ALGORITHMS UNIT - 1 Front 1= rear 1= 4. So when one element comes in the first queue then front 0 and Rear 0 are initialized to 1 and when element comes in the second queue then Front 1 and Rear 1 are initialized to 5. Then Rear are incremented by one after every insertion & decremented by one after every deletion. FIFO queue. A queue in which the first item added is always the first one out. LIFO queue. A queue in which the item most recently added is always the first one out. Priority queue. A queue in which the items are sorted so that the highest priority item is always the next one to be extracted. Life critical systems. Systems on which we depend for safety and which may result in death or injury if they fail: medical monitoring industrial plant monitoring and control and aircraft control systems are examples of life critical systems. Real time systems. Systems in which time is a constraint. A system which must respond to some event (e.g., the change in attitude of an aircraft caused by some atmospheric event like wind shear) within a fixed time to maintain stability or continue correct operation (e.g. the aircraft systems must make necessary adjustments to the control surfaces before the aircraft falls out of the sky!). What is Linked List? When we want to work with an unknown number of data values, we use a linked list data structure to organize that data. The linked list is a linear data structure that contains a sequence of elements such that each element links to its next element in the sequence. Each element in a linked list is called "Node". A singly linked list is a type of linked list that is unidirectional, that is, it can be traversed in only one direction from head to the last node (tail). Each element in a linked list is called a node. A single node contains data and a pointer to the next node which helps in maintaining the structure of the list. The first node is called the head; it points to the first node of the list and helps us access every other element in the list. The last node, also sometimes called the tail, points to NULL which helps us in determining when
  • 21. DATA STRUCTURES & ALGORITHMS UNIT - 1 the listen Why Linked List? Arrays can be used to store linear data of similar types, but arrays have the following limitations.  The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage.  Insertion of a new element / Deletion of a existing element in an array of elements is expensive: The room has to be created for the new elements and to create room existing elements have to be shifted but in Linked list if we have the head node then we can traverse to any node through it and insert new node at the required position. For example, in a system, if we maintain a sorted list of IDs in an array id[]. id[] = [1000, 1010, 1050, 2000, 2040]. And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000). Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved due to this so much work is being done which affects the efficiency of the code. Operations on Single Linked List The following operations are performed on a Single Linked List  Insertion  Deletion  Display Before we implement actual operations, first we need to set up an empty list. First, perform the following steps before implementing actual operations.  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.
  • 22. DATA STRUCTURES & ALGORITHMS UNIT - 1 Insertion In a single linked list, the insertion operation can be performed in three ways. They are as follows... 1. Inserting At Beginning of the list 2. Inserting At End of the list 3. Inserting At Specific location in the list Inserting At Beginning of the list We can use the following steps to insert a new node at beginning of the single linked list...  Step 1 - Create a newNode with given value.  Step 2 - Check whether list is Empty (head == NULL)  Step 3 - If it is Empty then, set newNode→next = NULL and head = newNode.  Step 4 - If it is Not Empty then, set newNode→next = head and head = newNode. Inserting At End of the list We can use the following steps to insert a new node at end of the single linked list...  Step 1 - Create a newNode with given value and newNode → next as NULL.  Step 2 - Check whether list is Empty (head == NULL).  Step 3 - If it is Empty then, set head = newNode.  Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.  Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list (until temp → next is equal to NULL).  Step 6 - Set temp → next = newNode. Inserting At Specific location in the list (After a Node) We can use the following steps to insert a new node after a node in the single linked list...  Step 1 - Create a newNode with given value.  Step 2 - Check whether list is Empty (head == NULL)  Step 3 - If it is Empty then, set newNode → next = NULL and head = newNode.  Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.  Step 5 - Keep moving the temp to its next node until it reaches to the node after which we want to insert the newNode (until temp1 → data is equal to location, here location is the node value after which we want to insert the newNode).  Step 6 - Every time check whether temp is reached to last node or not. If it is reached to last node then display 'Given node is not found in the list!!! Insertion not possible!!!' and terminate the function. Otherwise move the temp to next node.  Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp → next = newNode' Deletion In a single linked list, the deletion operation can be performed in three ways. They are as follows... 1. Deleting from Beginning of the list 2. Deleting from End of the list 3. Deleting a Specific Node
  • 23. DATA STRUCTURES & ALGORITHMS UNIT - 1 Deleting from Beginning of the list We can use the following steps to delete a node from beginning of the single linked list...  Step 1 - Check whether list is Empty (head == NULL)  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 a Node pointer 'temp' and initialize with head.  Step 4 - Check whether list is having only one node (temp → next == NULL)  Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list conditions)  Step 6 - If it is FALSE then set head = temp → next, and delete temp. Deleting from End of the list We can use the following steps to delete a node from end of the single linked list...  Step 1 - Check whether list is Empty (head == NULL)  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 == NULL)  Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate 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 it reaches to the last node in the list. (until temp1 → next == NULL)  Step 7 - Finally, Set temp2 → next = NULL and delete temp1. Deleting a Specific Node from the list We can use the following steps to delete a specific node from the single linked list...  Step 1 - Check whether list is Empty (head == NULL)  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 or not  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 == head).  Step 9 - If temp1 is the first node then move the head to the next node (head = head → next) and delete temp1.  Step 10 - If temp1 is not first node then check whether it is last node in the list (temp1 → next == NULL).  Step 11 - If temp1 is last node then set temp2 → next = NULL and delete temp1 (free(temp1)).
  • 24. DATA STRUCTURES & ALGORITHMS UNIT - 1  Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 → next and delete temp1 (free(temp1)). Displaying a Single Linked List We can use the following steps to display the elements of a single linked list...  Step 1 - Check whether list is Empty (head == NULL)  Step 2 - If it is Empty then, display 'List is Empty!!!' and terminate the function.  Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.  Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last node  Step 5 - Finally display temp → data with arrow pointing to NULL (temp → data ---> NULL). POLYNOMIAL ADDITION Given two polynomial numbers represented by a linked list. Write a function that add these lists means add the coefficients that have same variable powers. Example: Input: 1st number = 5x2 + 4x1 + 2x0 2nd number = -5x1 - 5x0 Output: 5x2-1x1-3x0 Input: 1st number = 5x3 + 4x2 + 2x0 2nd number = 5x^1 - 5x^0 Output: 5x3 + 4x2 + 5x1 - 3x0 Addition of polynomials can be solved in two methods.
  • 25. DATA STRUCTURES & ALGORITHMS UNIT - 1 Algorithm Input − Polynomial p1 and p2 represented as a linked list. Step 1: loop around all values of linked list and follow step 2& 3. Step 2: if the value of a node’s exponent is greater copy this node to result node and head towards the next node. Step 3: if the values of both node’s exponent is same add the coefficients and then copy the added value with node to the result. Step 4: Print the resultant node. (i) By arranging the like terms together and then add. For example: 1. Add: 5x + 3y, 4x – 4y + z and -3x + 5y + 2z First we need to write in the addition form. Thus, the required addition = (5x + 3y) + (4x – 4y + z) + (-3x + 5y + 2z) = 5x + 3y + 4x – 4y + z - 3x + 5y + 2z Now we need to arrange all the like terms and then all the like terms are added. 5x + 4x - 3x + 3y – 4y + 5y + z + 2z = 6x + 4y + 3z 2. Add: 3a2 + ab – b2 , -a2 + 2ab + 3b2 and 3a2 – 10ab + 4b2 First we need to write in the addition form. Thus, the required addition = (3a2 + ab – b2) + (-a2 + 2ab + 3b2) + (3a2 – 10ab + 4b2) = 3a2 + ab – b2 - a2 + 2ab + 3b2 + 3a2 – 10ab + 4b2 Here, we need to arrange the like terms and then add = 3a2 - a2 + 3a2 + ab + 2ab – 10ab – b2 + 3b2 + 4b2 = 5a2 – 7ab + 6b2 By arranging expressions in lines so that the like terms with their signs are one below the other i.e. like terms are in same vertical column and then add thedifferent groups of like terms. For example: 1. Add: 7a + 5b, 6a – 6b + 3c and -5a + 7b + 4c First we will arrange the three expressions one below the other, placing the like terms in the same column.
  • 26. DATA STRUCTURES & ALGORITHMS UNIT - 1 Now the like terms are added by adding their coefficients with their signs. Therefore, adding 7a + 5b, 6a – 6b + 3c and -5a + 7b + 4c is 8a + 6b + 7c. 2. Add: 3x3 – 5x2 + 8x + 10, 15x3 – 6x – 23, 9x2 – 4x + 15 and -8x3 + 2x2 – 7x. First we will arrange the like terms in the vertical column and then the like terms are added by adding their coefficients with their signs. Therefore, adding 3x3 – 5x2 + 8x + 10, 15x3 – 6x – 23, 9x2 – 4x + 15 and - 8x3 + 2x2 – 7x is 10x3 + 6x2 – 9x + 2. Thus, we have learnt how to solve addition of polynomials in both the methods.