SlideShare a Scribd company logo
What is Data Structure
Data Structure is a way to store and organize data so that it can be used efficiently.
Our Data Structure tutorial includes all topics of Data Structure such as Array, Pointer, Structure,
Linked List, Stack, Queue, Graph, Searching, Sorting, Programs, etc.
What is Data Structure?
The data structure name indicates itself that organizing the data in memory. There are many
ways of organizing the data in the memory as we have already seen one of the data structures,
i.e., array in C language. Array is a collection of memory elements in which data is stored
sequentially, i.e., one after another. In other words, we can say that array stores the elements in a
continuous manner. This organization of data is done with the help of an array of data structures.
There are also other ways to organize the data in memory. Let's see the different types of data
structures.
The data structure is not any programming language like C, C++, java, etc. It is a set of
algorithms that we can use in any programming language to structure the data in the memory.
To structure the data in memory, 'n' number of algorithms were proposed, and all these
algorithms are known as Abstract data types. These abstract data types are the set of rules.
Types of Data Structures
There are two types of data structures:
 Primitive data structure
 Non-primitive data structure
Primitive Data structure
Primitive Data Structures
1. Primitive Data Structures are the data structures consisting of the numbers and
the characters that come in-built into programs.
2. These data structures can be manipulated or operated directly by machine-level
instructions.
3. Basic data types like Integer, Float, Character, and Boolean come under the
Primitive Data Structures.
4. These data types are also called Simple data types, as they contain characters that
can't be divided further
Non-Primitive Data Structures
1. Non-Primitive Data Structures are those data structures derived from Primitive
Data Structures.
2. These data structures can't be manipulated or operated directly by machine-level
instructions.
3. The focus of these data structures is on forming a set of data elements that is
either homogeneous (same data type) or heterogeneous (different data types).
4. Based on the structure and arrangement of data, we can divide these data
structures into two sub-categories -
a. Linear Data Structures
b. Non-Linear Data Structures
The primitive data structures are primitive data types. The int, char, float, double, and pointer are
the primitive data structures that can hold a single value.
Non-Primitive Data structure
The non-primitive data structure is divided into two types:
 Linear data structure
 Non-linear data structure
Linear Data Structure:-
The arrangement of data in a sequential manner is known as a linear data structure. The data
structures used for this purpose are Arrays, Linked list, Stacks, and Queues. In these data
structures, one element is connected to only one another element in a linear form.
When one element is connected to the 'n' number of elements known as a non-linear data
structure. The best example is trees and graphs. In this case, the elements are arranged in a
random manner.
Data structures can also be classified as:
 Static data structure: It is a type of data structure where the size is allocated at the
compile time. Therefore, the maximum size is fixed.
 Dynamic data structure: It is a type of data structure where the size is allocated at the
run time. Therefore, the maximum size is flexible.



Major Operations
 The major or the common operations that can be performed on the data structures are:
 Searching: We can search for any element in a data structure.
 Sorting: We can sort the elements of a data structure either in an ascending or
descending order.
 Insertion: We can also insert the new element in a data structure.
 Updation: We can also update the element, i.e., we can replace the element with another
element.
 Deletion: We can also perform the delete operation to remove the element from the data
structure.
Advantages of Data Structure
 Efficiency: If the choice of a data structure for implementing a particular ADT is proper,
it makes the program very efficient in terms of time and space.
 Reusability: The data structure provides reusability means that multiple client programs
can use the data structure.
 Abstraction: The data structure specified by an ADT also provides the level of
abstraction. The client cannot see the internal working of the data structure, so it does not
have to worry about the implementation part. The client can only see the interface.
Data Structure Algorithm
An algorithm is a process or a set of rules required to perform calculations or some other problem-
solving operations especially by a computer. The formal definition of an algorithm is that it contains the
finite set of instructions which are being carried in a specific order to perform the specific task. It is not
the complete program or code; it is just a solution (logic) of a problem, which can be represented either
as an informal description using a Flowchart or Pseudocode.
Characteristics of an Algorithm
The following are the characteristics of an algorithm:
 Input: An algorithm has some input values. We can pass 0 or some input value to an
algorithm.
 Output: We will get 1 or more output at the end of an algorithm.
 Unambiguity: An algorithm should be unambiguous which means that the instructions in
an algorithm should be clear and simple.
 Finiteness: An algorithm should have finiteness. Here, finiteness means that the
algorithm should contain a limited number of instructions, i.e., the instructions should be
countable.
 Effectiveness: An algorithm should be effective as each instruction in an algorithm
affects the overall process.
 Language independent: An algorithm must be language-independent so that the
instructions in an algorithm can be implemented in any of the languages with the same
output.
Dataflow of an Algorithm
 Problem: A problem can be a real-world problem or any instance from the real-world
problem for which we need to create a program or the set of instructions. The set of
instructions is known as an algorithm.
 Algorithm: An algorithm will be designed for a problem which is a step by step
procedure.
 Input: After designing an algorithm, the required and the desired inputs are provided to
the algorithm.
 Processing unit: The input will be given to the processing unit, and the processing unit
will produce the desired output.
 Output: The output is the outcome or the result of the program.
Why do we need Algorithms?
We need algorithms because of the following reasons:
 Scalability: It helps us to understand the scalability. When we have a big real-world
problem, we need to scale it down into small-small steps to easily analyze the problem.
 Performance: The real-world is not easily broken down into smaller steps. If the
problem can be easily broken into smaller steps means that the problem is feasible.
Example of an Algorithm
Step 1: First, we will cut the lemon into half.
Step 2: Squeeze the lemon as much you can and take out its juice in a container.
Step 3: Add two tablespoon sugar in it.
Step 4: Stir the container until the sugar gets dissolved.
Step 5: When sugar gets dissolved, add some water and ice in it.
Step 6: Store the juice in a fridge for 5 to minutes.
Step 7: Now, it's ready to drink.
The above real-world can be directly compared to the definition of the algorithm. We cannot
perform the step 3 before the step 2, we need to follow the specific order to make lemon juice.
An algorithm also says that each and every instruction should be followed in a specific order to
perform a specific task.
The following are the steps required by the to add two numbers entered by the user.
Step 1: Start
Step 2: Declare three variables a, b, and sum.
Step 3: Enter the values of a and b.
Step 4: Add the values of a and b and store the result in the sum variable, i.e., sum=a+b.
Step 5: Print sum
Step 6: Stop
Factors of an Algorithm
The following are the factors that we need to consider for designing an algorithm:
 Modularity: If any problem is given and we can break that problem into small-small
modules or small-small steps, which is a basic definition of an algorithm, it means that
this feature has been perfectly designed for the algorithm.
 Correctness: The correctness of an algorithm is defined as when the given inputs
produce the desired output, which means that the algorithm has been designed algorithm.
The analysis of an algorithm has been done correctly.
 Maintainability: Here, maintainability means that the algorithm should be designed in a
very simple structured way so that when we redefine the algorithm, no major change will
be done in the algorithm.
 Functionality: It considers various logical steps to solve the real-world problem.
 Robustness: Robustness means that how an algorithm can clearly define our problem.
 User-friendly: If the algorithm is not user-friendly, then the designer will not be able to
explain it to the programmer.
 Simplicity: If the algorithm is simple then it is easy to understand.
 Extensibility: If any other algorithm designer or programmer wants to use your
algorithm then it should be extensible.
Importance of Algorithms
1. Theoretical importance: When any real-world problem is given to us and we break the
problem into small-small modules. To break down the problem, we should know all the
theoretical aspects.
2. Practical importance: As we know that theory cannot be completed without the
practical implementation. So, the importance of algorithm can be considered as both
theoretical and practical.
Issues of Algorithms
The following are the issues that come while designing an algorithm:
 How to design algorithms: As we know that an algorithm is a step-by-step procedure so
we must follow some steps to design an algorithm.
 How to analyze algorithm efficiency
Time Complexity of Sorting Algorithms
We might have come across various instances where we need to process the data in a specific
format without taking any further delay and the same in case of unsorted data processed with
higher speed so that results could be put to some use. In such instances, we use sorting
algorithms so that the desired efficiency is achieved. In this article, we will discuss various types
of sorting algorithms with higher emphasis on time complexities. But, before moving any
further, let's understand what complexity is and what's so important to talk about it.
Complexity
Complexity has no formal definition at all. It just defines the rate of efficiency at which a task is
executed. In data structures and algorithms, there are two types of complexities that determine
the efficiency of an algorithm. They are:
Space Complexity: Space complexity is the total memory consumed by the program for its
execution.
Time Complexity: It is defined as the times in number instruction, in particular, is expected to
execute rather than the total time is taken. Since time is a dependent phenomenon, time
complexity may vary on some external factors like processor speed, the compiler used, etc.
In computer science, the time complexity of an algorithm is expressed in big O notation. Let's
discuss some time complexities.
O(1): This denotes the constant time. 0(1) usually means that an algorithm will have constant
time regardless of the input size. Hash Maps are perfect examples of constant time.
O(log n): This denotes logarithmic time. O(log n) means to decrease with each instance for the
operations. Binary search trees are the best examples of logarithmic time.
O(n): This denotes linear time. O(n) means that the performance is directly proportional to the
input size. In simple terms, the number of inputs and the time taken to execute those inputs will
be proportional or the same. Linear search in arrays is the best example of linear time
complexity.
The Data Type is basically a type of data that can be used in different computer program. It
signifies the type like integer, float etc, the space like integer will take 4-bytes, character will
take 1-byte of space etc.
The abstract datatype is special kind of datatype, whose behavior is defined by a set of values
and set of operations. The keyword “Abstract” is used as we can use these datatypes, we can
perform different operations. But how those operations are working that is totally hidden from
the user. The ADT is made of with primitive datatypes, but operation logics are hidden.
Some examples of ADT are Stack, Queue, List etc.
Let us see some operations of those mentioned ADT −
Stack −
isFull(), This is used to check whether stack is full or not
isEmpry(), This is used to check whether stack is empty or not
push(x), This is used to push x into the stack
pop(), This is used to delete one element from top of the stack
peek(), This is used to get the top most element of the stack
size(), this function is used to get number of elements present into the stack
Queue −
isFull(), This is used to check whether queue is full or not
isEmpry(), This is used to check whether queue is empty or not
insert(x), This is used to add x into the queue at the rear end
delete(), This is used to delete one element from the front end of the queue
size(), this function is used to get number of elements present into the queue
List −
size(), this function is used to get number of elements present into the list
insert(x), this function is used to insert one element into the list
remove(x), this function is used to remove given element from the list
get(i), this function is used to get element at position i
replace(x, y), this function is used to replace x with y value
O(n2): This denotes quadratic time. O(n2) means that the performance is directly proportional to
the square of the input taken. In simple, the time taken for execution will take square times the
input size. Nested loops are perfect examples of quadratic time complexity.
Array in Data Structure
Arrays are defined as the collection of similar types of data items stored at contiguous memory
locations. It is one of the simplest data structures where each data element can be randomly
accessed by using its index number.
In C programming, they are the derived data types that can store the primitive type of data such
as int, char, double, float, etc. For example, if we want to store the marks of a student in 6
subjects, then we don't need to define a different variable for the marks in different subjects.
Instead, we can define an array that can store the marks in each subject at the contiguous
memory locations.
Properties of array
There are some of the properties of an array that are listed as follows -
 Each element in an array is of the same data type and carries the same size that is 4 bytes.
 Elements in the array are stored at contiguous memory locations from which the first
element is stored at the smallest memory location.
 Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Representation of an array
 We can represent an array in various ways in different programming languages. As an
illustration, let's see the declaration of array in C language –
We can represent an array in various ways in different programming languages. As an
illustration, let's see the declaration of array in C language -
x
As per the above illustration, there are some of the following important points -
 Index starts with 0.
 The array's length is 10, which means we can store 10 elements.
 Each element in the array can be accessed via its index.
Why are arrays required?
Arrays are useful because -
 Sorting and searching a value in an array is easier.
 Arrays are best to process multiple values quickly and easily.
 Arrays are good for storing multiple values in a single variable - In computer
programming, most cases require storing a large number of data of a similar type. To
store such an amount of data, we need to define a large number of variables. It would be
very difficult to remember the names of all the variables while writing the programs.
Instead of naming all the variables with a different name, it is better to define an array
and store all the elements into it.
Memory allocation of an array
As stated above, all the data elements of an array are stored at contiguous locations in the main
memory. The name of the array represents the base address or the address of the first element in
the main memory. Each element of the array is represented by proper indexing.
We can define the indexing of an array in the below ways -
1. 0 (zero-based indexing): The first element of the array will be arr[0].
2. 1 (one-based indexing): The first element of the array will be arr[1].
3. n (n - based indexing): The first element of the array can reside at any random index
number.
In the above image, we have shown the memory allocation of an array arr of size 5. The array
follows a 0-based indexing approach. The base address of the array is 100 bytes. It is the address
of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each element will take 4 bytes
in the memory.
How to access an element from the array?
We required the information given below to access any random element from the array -
 Base Address of the array.
 Size of an element in bytes.
 Type of indexing, array follows.
The formula to calculate the address to access an array element -
1. Byte address of element A[i] = base address + size * ( i - first index)
Here, size represents the memory taken by the primitive data types. As an instance, int takes 2
bytes, float takes 4 bytes of memory space in C programming.
We can understand it with the help of an example -
Suppose an array, A[-10 ..... +2 ] having Base address (BA) = 999 and size of an element = 2
bytes, find the location of A[-1].
L(A[-1]) = 999 + 2 x [(-1) - (-10)]
= 999 + 18
= 1017
Stack in Data Structure
A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has
one end, whereas the Queue has two ends (front and rear). It contains only one pointer top
pointer pointing to the topmost element of the stack. Whenever an element is added in the stack,
it is added on the top of the stack, and the element can be deleted only from the stack. In other
words, a stack can be defined as a container in which insertion and deletion can be done from
the one end known as the top of the stack.
Some key points related to stack
 It is called as stack because it behaves like a real-world stack, piles of books, etc.
 A Stack is an abstract data type with a pre-defined capacity, which means that it can store
the elements of a limited size.
 It is a data structure that follows some order to insert and delete the elements, and that
order can be LIFO or FILO.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below figure there are five memory
blocks in the stack; therefore, the size of the stack is 5.
Suppose we want to store the elements in a stack and let's assume that stack is empty. We have
taken the stack of size 5 as shown below in which we are pushing the elements one by one until
the stack becomes full.
Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it goes
from the top to the bottom when we were entering the new element in the stack. The stack gets
filled up from the bottom to the top.
When we perform the delete operation on the stack, there is only one way for entry and exit as
the other end is closed. It follows the LIFO pattern, which means that the value entered first will
be removed last. In the above case, the value 5 is entered first, so it will be removed only after
the deletion of all the other elements.
Standard Stack Operations
The following are some common operations implemented on the stack:
 push(): When we insert an element in a stack then the operation is known as a push. If
the stack is full then the overflow condition occurs.
 pop(): When we delete an element from the stack, the operation is known as a pop. If the
stack is empty means that no element exists in the stack, this state is known as an
underflow state.
 isEmpty(): It determines whether the stack is empty or not.
 isFull(): It determines whether the stack is full or not.'
 peek(): It returns the element at the given position.
 count(): It returns the total number of elements available in a stack.
 change(): It changes the element at the given position.
 display(): It prints all the elements available in the stack.
PUSH operation
The steps involved in the PUSH operation is given below:
 Before inserting an element in a stack, we check whether the stack is full.
 If we try to insert the element in a stack, and the stack is full, then the overflow condition
occurs.
 When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
 When the new element is pushed in a stack, first, the value of the top gets incremented,
i.e., top=top+1, and the element will be placed at the new position of the top.
 The elements will be inserted until we reach the max size of the stack.
POP operation
The steps involved in the POP operation is given below:
 Before deleting the element from the stack, we check whether the stack is empty.
 If we try to delete the element from the empty stack, then the underflow condition
occurs.
 If the stack is not empty, we first access the element which is pointed by the top
 Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
Applications of Stack
The following are the applications of the stack:
 Balancing of symbols: Stack is used for balancing a symbol. For example, we have the
following program:
1. int main()
2. {
3. cout<<"Hello";
4. cout<<"javaTpoint";
5. }
As we know, each program has an opening and closing braces; when the opening braces come,
we push the braces in a stack, and when the closing braces appear, we pop the opening braces
from the stack. Therefore, the net value comes out to be zero. If any symbol is left in the stack, it
means that some syntax occurs in a program.
 String reversal: Stack is also used for reversing a string. For example, we want to
reverse a "javaTpoint" string, so we can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character.
After pushing all the characters, we start taking out the character one by one until we
reach the bottom of the stack.
 UNDO/REDO: It can also be used for performing UNDO/REDO operations. For
example, we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text
written in an editor is abc. So, there are three states, a, ab, and abc, which are stored in a
stack. There would be two stacks in which one stack shows UNDO state, and the other
shows REDO state.
If we want to perform UNDO operation, and want to achieve 'ab' state, then we
implement pop operation.
 Recursion: The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of
the function are maintained.
 DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the
stack data structure.
 Backtracking: Suppose we have to create a path to solve a maze problem. If we are
moving in a particular path, and we realize that we come on the wrong way. In order to
come at the beginning of the path to create a new path, we have to use the stack data
structure.
 Expression conversion: Stack can also be used for expression conversion. This is one of
the most important applications of stack. The list of the expression conversion is given
below:
Notation in Stack
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.
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
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
Conversion of Prefix to Postfix expression
Before understanding the conversion of prefix to postfix conversion, we should know
about the prefix and postfix expressions separately.
What is Prefix conversion?
An infix expression is an expression in which the operators are written between the two
operands. If we move the operator before the operands then it is known as a prefix
expression. In other words, prefix expression can be defined as an expression in which all
the operators precede the two operands.
For example:
If the infix expression is given as: A + B * C
As we know that the multiplication operator * has a higher precedence than the addition
operator. First, multiplication operator will move before operand B shown as below:
A + * B C
Once the multiplication operator is moved before 'B' operand, addition operator will move
before the operand 'A' shown as below:
+ A * B C
Evaluation of Prefix Expression using Stack
Step 1: Initialize a pointer 'S' pointing to the end of the expression.
Step 2: If the symbol pointed by 'S' is an operand then push it into the stack.
Step 3: If the symbol pointed by 'S' is an operator then pop two operands from the stack.
Perform the operation on these two operands and stores the result into the stack.
Step 4: Decrement the pointer 'S' by 1 and move to step 2 as long as the symbols left in
the expression.
Step 5: The final result is stored at the top of the stack and return it.
Step 6: End
Let's understand the evaluation of prefix expression through an example.
Expression: +, -, *, 2, 2, /, 16, 8, 5
First, we will reverse the expression given above.
Expression: 5, 8, 16, /, 2, 2, *, -, +
We will use the stack data structure to evaluate the prefix expression.
Symbol Scanned Stack
5 5
8 5, 8
16 5, 8, 16
/ 5, 2
2 5, 2, 2
2 5, 2, 2, 2
* 5, 2, 4
- 5, 2
+ 7
The final result of the above expression is 7.
What is Postfix expression?
If we move the operators after the operands then it is known as a postfix expression. In
other words, postfix expression can be defined as an expression in which all the operators
are present after the operands.
For example:
If the infix expression is A + B * C
As we know that the multiplication operator has a higher precedence than the addition
operator, so multiplication operator will move after the operands B and C shown as below:
A + B C *
Once the multiplication operator is moved after the operand C, then the addition operator
will come after the multiplication operator shown as below:
A B C * +
Evaluation of Postfix expression using Stack
Algorithm for the evaluation of postfix expression using stack:
Step 1: Create an empty stack used for storing the operands.
Step 2: Scan each element of an expression one be one and do the following:
o If the element is an operand then push it into the stack.
o If the element is an operator then pop two operands from the stack. Perform
operation on these operands. Push the final result into the stack.
Step 3: When the expression is scanned completely, the value available in the stack would
be the final output of the given expression.
Let's understand the evaluation of postfix expression using stack through an
example.
If the expression is: 5, 6, 2, +, *, 12, 4, /, -
Symbol Scanned Stack
5 5
6 5, 6
2 5, 6, 2
+ 5, 8
* 40
12 40, 12
4 40, 12, 4
/ 40, 3
- 37
The result of the above expression is 37.
Conversion of Prefix to Postfix Expression
Here, we will see the conversion of prefix to postfix expression using a stack data structure.
Rules for prefix to postfix expression using stack data structure:
o Scan the prefix expression from right to left, i.e., reverse.
o If the incoming symbol is an operand then push it into the stack.
o If the incoming symbol is an operator then pop two operands from the stack. Once
the operands are popped out from the stack, we add the incoming symbol after
the operands. When the operator is added after the operands, then the expression
is pushed back into the stack.
o Once the whole expression is scanned, pop and print the postfix expression from
the stack.
f the expression is: * - A / B C - / A K L
Symbols to
be scanned
Action Stack Description
L Push L into the stack L
K Push K into the stack L, K
A Push A into the stack L, K, A
/ Pop A from the stack
Pop K from the stack
Push A K / into the stack
L, A K / Pop two operands from the stack, i.e., A an
K. Add '/' operator after K operand, i.e., AK
Push AK/ into the stack.
- Pop A K / and L from the
stack.
Push (A K / L -) into the stack
A K / L - Pop two operands from the stack, i.e., AK
and L. Add '-' operator after 'L' operand.
C Push C into the stack AK/L-, C
B Push B into the stack AK/L-, C,
B
/ Pop B and C from the stack.
Push BC/ into the stack.
AK/L-,
BC/
Pop two operands from the stack, i.e., B an
C. Add '/' operator after C operator, i.e., BC
Push BC/ into the stack.
A Push A into the stack AK/L-,
BC/, A
- Pop BC/ and A from the
stack. Push ABC/- into the
stack.
AK/L-,
ABC/-
Pop two operands from the stack, i.e., A an
BC/. Add '-' operator after '/'.
* Pop ABC/- and AK/L- from
the stack. Push ABC/AK/L-*
into the stack.
ABC/-
AK/L-*
Pop two operands from the stack, i.e., ABC/
, and AK/L- . Add '*' operator after L and '
operator, i.e., ABC/-AK/L-*.
Conversion of Postfix to Prefix expression
What is Postfix expression?
A postfix expression is said to be an expression in which the operator appears after the
operands. It can be written as:
(operand) (operand) (operator)
For example:
If the expression is:
(A+B) * (C+D)
Firstly, operator precedence rules will be applied to the above expression. Since the
parenthesis has higher precedence than the multiplication operator; therefore '+' will be
resolved first, and the + operator will come after AB and CD shown as below:
(AB+) * (CD+)
Now, the multiplication operator will move after CD+ shown as below:
AB+ CD+*
What is Prefix Expression?
A prefix expression is said to be an expression in which the operator appears before the
operands.
For example:
If the expression is given as:
(A+B) * (C+D)
Firstly, operator precedence rules will be applied to the above expression. Since the
parenthesis has higher precedence than the multiplication operator; therefore, the '+'
operator will be resolved first, and the '+' operator will move before the operands AB and
CD shown as below:
(+AB) * (+CD)
Now, the multiplication operator will move before the +AB shown as below:
*+AB+CD
Conversion of Postfix to Prefix expression
There are two ways of converting a postfix into a prefix expression:
1. Conversion of Postfix to Prefix expression manually.
2. Conversion of Postfix to Prefix expression using stack.
Pointer
Pointer is used to points the address of the value stored anywhere in the computer memory. To
obtain the value stored at the location is known as dereferencing the pointer. Pointer improves
the performance for repetitive process such as:
 Traversing String
 Lookup Tables
 Control Tables
 Tree Structures
Pointer Details
 Pointer arithmetic: There are four arithmetic operators that can be used in pointers: ++,
--, +, -
 Array of pointers: You can define arrays to hold a number of pointers.
 Pointer to pointer: C allows you to have pointer on a pointer and so on.
 Passing pointers to functions in C: Passing an argument by reference or by address
enable the passed argument to be changed in the calling function by the called function.
 Return pointer from functions in C: C allows a function to return a pointer to the local
variable, static variable and dynamically allocated memory as well.
Program
Pointer
1. #include <stdio.h>
2.
3. int main( )
4. {
5. int a = 5;
6. int *b;
7. b = &a;
8.
9. printf ("value of a = %dn", a);
10. printf ("value of a = %dn", *(&a));
11. printf ("value of a = %dn", *b);
12. printf ("address of a = %un", &a);
13. printf ("address of a = %dn", b);
14. printf ("address of b = %un", &b);
15. printf ("value of b = address of a = %u", b);
16. return 0;
17. }
Output
1. value of a = 5
2. value of a = 5
3. address of a = 3010494292
4. address of a = -
1284473004
5. address of b = 3010494296
6. value of b = address of a = 3010494292
String in Data Structure
String is an array of characters and terminated by a null character (0). The null character is not
placed by the user, the compiler places it at the end of string automatically.
The difference between an array and a string is that the compiler does not place null character at
the end of array while in string, compiler places null character.
Here is the syntax of string in C language,
char myStr[size];
Here,
myStr: The string
size: Set the size of string
Initialize string in C language like show below −
char myStr[size] = “string”;
char myStr[size] = { ‘s’,’t’,’r’,’i’,’n’,’g’,’0’ };
The following table displays functions of string in C language.
Function Purposes
strcpy(s1,
s2)
Copies string s2 into string s2
strcat(s1,
s2)
Concatenates s2 onto end of s1
strlen(s1) Returns the length of string s1
strcmp(s1,
s2)
Returns 0 when s1 and s2 are same Greater than 0 when ASCII value of s1 is
greater than s2 Lesser than 0 when ASCII value of s1 is lesser than s2
strchr(s1,
ch)
Returns the pointer to the first occurence of character ch in string s1
strstr(s1, s2)
Returns the pointer to the first occurence of string s2 in string s1
List in Data Structure
The list can be defined as an abstract data type in which the elements are stored in an
ordered manner for easier and efficient retrieval of the elements. List Data Structure allows
repetition that means a single piece of data can occur more than once in a list. In the case
of multiple entries of the same data, each entry of that repeating data is considered as a
distinct item or entry. It is very much similar to the array but the major difference between
the array and the list data structure is that array stores only homogenous data in them
whereas the list (in some programming languages) can store heterogeneous data items
in its object. List Data Structure is also known as a sequence.
The list can be called Dynamic size arrays, which means their size increased as we go on
adding data in them and we need not to pre-define a static size for the list.
For example,
numbers = [ 1, 2, 3, 4, 5]
In this example, 'numbers' is the name of the List Data Structure object and it has five
items stored in it. In the object named numbers, we have stored all the elements of
numeric type. In the list, the indexing starts from zero, which means if we want to access
or retrieve the first element of this list then we need to use index zero and similarly
whenever we want to access any element from this list named numbers. In other words,
we can say that element 1 is on the index 0 and element 2 is on index 1 and similarly for
further all elements.
Mixed_data = [205, 'Nirnay', 8.56]
In this second example, mixed_data is the name of the list object that stores the data of
different types. In the mixed_data list, we have stored data of three types, first one is the
integer type which is id '205', after the integer data we have stored a string type data
having the value 'Nirnay' stored at index 1 and at last the index value 2, we have stored a
float type data having the value '8.56'.
To access the elements of the mixed_data list, we need to follow the same approach as
defined in the previous example.
And we can add more data to these defined List objects and that will get appended at the
last of the list. For example, if we add another data in the mixed_data list, it will get
appended after the float value object having value '8.56'. And we can add repeating values
to these list-objects.
Queue:
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at
both its ends. One end is always used to insert data (enqueue) and the other is used to remove
data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will
be accessed first.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first. More real-world examples can be seen as queues at the ticket windows and bus-
stops.
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.
 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
Example
bool isfull() {
if(rear == MAXSIZE - 1)
return true;
else
return false;
}
isempty()
Algorithm of isempty() function −
Algorithm
begin procedure isempty
if front is less than MIN OR front is greater than rear
return true
else
return false
endif
end procedure
If the value of front is less than MIN or 0, it tells that the queue is not yet initialized, hence
empty.
Here's the C programming code −
Example
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.
Queue Enqueue
Algorithm for enqueue operation
procedure enqueue(data)
if queue is full
return overflow
endif
rear ← rear + 1
queue[rear] ← data
return true
end procedure
Implementation of enqueue() in C programming language −
Example
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
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;
}

More Related Content

Similar to Data Structure Notes unit 1.docx

Feature Engineering in Machine Learning
Feature Engineering in Machine LearningFeature Engineering in Machine Learning
Feature Engineering in Machine Learning
Knoldus Inc.
 
Unit 1 dsa
Unit 1 dsaUnit 1 dsa
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
JohnStuart83
 
employee turnover prediction document.docx
employee turnover prediction document.docxemployee turnover prediction document.docx
employee turnover prediction document.docx
rohithprabhas1
 
Data structure
Data structureData structure
Data structure
Prof. Dr. K. Adisesha
 
Iare ds lecture_notes_2
Iare ds lecture_notes_2Iare ds lecture_notes_2
Iare ds lecture_notes_2
RajSingh734307
 
Data structure and algorithm.
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm.
Abdul salam
 
computer notes - Circular list
computer notes - Circular listcomputer notes - Circular list
computer notes - Circular list
ecomputernotes
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
SisayNegash4
 
How to understand and implement regression analysis
How to understand and implement regression analysisHow to understand and implement regression analysis
How to understand and implement regression analysis
ClaireWhittaker5
 
Automated Essay Grading using Features Selection
Automated Essay Grading using Features SelectionAutomated Essay Grading using Features Selection
Automated Essay Grading using Features Selection
IRJET Journal
 
Lec1
Lec1Lec1
Lec1
Lec1Lec1
Lec1
Saad Gabr
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
Adams Sidibe
 
Unit 1-problem solving with algorithm
Unit 1-problem solving with algorithmUnit 1-problem solving with algorithm
Unit 1-problem solving with algorithm
rajkumar1631010038
 
IRJET- Machine Learning: Survey, Types and Challenges
IRJET- Machine Learning: Survey, Types and ChallengesIRJET- Machine Learning: Survey, Types and Challenges
IRJET- Machine Learning: Survey, Types and Challenges
IRJET Journal
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)
praveena p
 
Analysis modeling
Analysis modelingAnalysis modeling
Analysis modeling
Inocentshuja Ahmad
 
System and its types
System and its typesSystem and its types
System and its types
nidhipandey79
 
Lec 1 Ds
Lec 1 DsLec 1 Ds
Lec 1 Ds
Qundeel
 

Similar to Data Structure Notes unit 1.docx (20)

Feature Engineering in Machine Learning
Feature Engineering in Machine LearningFeature Engineering in Machine Learning
Feature Engineering in Machine Learning
 
Unit 1 dsa
Unit 1 dsaUnit 1 dsa
Unit 1 dsa
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
employee turnover prediction document.docx
employee turnover prediction document.docxemployee turnover prediction document.docx
employee turnover prediction document.docx
 
Data structure
Data structureData structure
Data structure
 
Iare ds lecture_notes_2
Iare ds lecture_notes_2Iare ds lecture_notes_2
Iare ds lecture_notes_2
 
Data structure and algorithm.
Data structure and algorithm. Data structure and algorithm.
Data structure and algorithm.
 
computer notes - Circular list
computer notes - Circular listcomputer notes - Circular list
computer notes - Circular list
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
How to understand and implement regression analysis
How to understand and implement regression analysisHow to understand and implement regression analysis
How to understand and implement regression analysis
 
Automated Essay Grading using Features Selection
Automated Essay Grading using Features SelectionAutomated Essay Grading using Features Selection
Automated Essay Grading using Features Selection
 
Lec1
Lec1Lec1
Lec1
 
Lec1
Lec1Lec1
Lec1
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
 
Unit 1-problem solving with algorithm
Unit 1-problem solving with algorithmUnit 1-problem solving with algorithm
Unit 1-problem solving with algorithm
 
IRJET- Machine Learning: Survey, Types and Challenges
IRJET- Machine Learning: Survey, Types and ChallengesIRJET- Machine Learning: Survey, Types and Challenges
IRJET- Machine Learning: Survey, Types and Challenges
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)
 
Analysis modeling
Analysis modelingAnalysis modeling
Analysis modeling
 
System and its types
System and its typesSystem and its types
System and its types
 
Lec 1 Ds
Lec 1 DsLec 1 Ds
Lec 1 Ds
 

Recently uploaded

How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
Chevonnese Chevers Whyte, MBA, B.Sc.
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 

Recently uploaded (20)

How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
Constructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective CommunicationConstructing Your Course Container for Effective Communication
Constructing Your Course Container for Effective Communication
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 

Data Structure Notes unit 1.docx

  • 1. What is Data Structure Data Structure is a way to store and organize data so that it can be used efficiently. Our Data Structure tutorial includes all topics of Data Structure such as Array, Pointer, Structure, Linked List, Stack, Queue, Graph, Searching, Sorting, Programs, etc. What is Data Structure? The data structure name indicates itself that organizing the data in memory. There are many ways of organizing the data in the memory as we have already seen one of the data structures, i.e., array in C language. Array is a collection of memory elements in which data is stored sequentially, i.e., one after another. In other words, we can say that array stores the elements in a continuous manner. This organization of data is done with the help of an array of data structures. There are also other ways to organize the data in memory. Let's see the different types of data structures. The data structure is not any programming language like C, C++, java, etc. It is a set of algorithms that we can use in any programming language to structure the data in the memory. To structure the data in memory, 'n' number of algorithms were proposed, and all these algorithms are known as Abstract data types. These abstract data types are the set of rules. Types of Data Structures There are two types of data structures:  Primitive data structure  Non-primitive data structure Primitive Data structure
  • 2. Primitive Data Structures 1. Primitive Data Structures are the data structures consisting of the numbers and the characters that come in-built into programs. 2. These data structures can be manipulated or operated directly by machine-level instructions. 3. Basic data types like Integer, Float, Character, and Boolean come under the Primitive Data Structures. 4. These data types are also called Simple data types, as they contain characters that can't be divided further Non-Primitive Data Structures 1. Non-Primitive Data Structures are those data structures derived from Primitive Data Structures. 2. These data structures can't be manipulated or operated directly by machine-level instructions. 3. The focus of these data structures is on forming a set of data elements that is either homogeneous (same data type) or heterogeneous (different data types).
  • 3. 4. Based on the structure and arrangement of data, we can divide these data structures into two sub-categories - a. Linear Data Structures b. Non-Linear Data Structures The primitive data structures are primitive data types. The int, char, float, double, and pointer are the primitive data structures that can hold a single value. Non-Primitive Data structure The non-primitive data structure is divided into two types:  Linear data structure  Non-linear data structure Linear Data Structure:- The arrangement of data in a sequential manner is known as a linear data structure. The data structures used for this purpose are Arrays, Linked list, Stacks, and Queues. In these data structures, one element is connected to only one another element in a linear form. When one element is connected to the 'n' number of elements known as a non-linear data structure. The best example is trees and graphs. In this case, the elements are arranged in a random manner. Data structures can also be classified as:  Static data structure: It is a type of data structure where the size is allocated at the compile time. Therefore, the maximum size is fixed.  Dynamic data structure: It is a type of data structure where the size is allocated at the run time. Therefore, the maximum size is flexible.    Major Operations  The major or the common operations that can be performed on the data structures are:  Searching: We can search for any element in a data structure.  Sorting: We can sort the elements of a data structure either in an ascending or descending order.  Insertion: We can also insert the new element in a data structure.
  • 4.  Updation: We can also update the element, i.e., we can replace the element with another element.  Deletion: We can also perform the delete operation to remove the element from the data structure. Advantages of Data Structure  Efficiency: If the choice of a data structure for implementing a particular ADT is proper, it makes the program very efficient in terms of time and space.  Reusability: The data structure provides reusability means that multiple client programs can use the data structure.  Abstraction: The data structure specified by an ADT also provides the level of abstraction. The client cannot see the internal working of the data structure, so it does not have to worry about the implementation part. The client can only see the interface. Data Structure Algorithm An algorithm is a process or a set of rules required to perform calculations or some other problem- solving operations especially by a computer. The formal definition of an algorithm is that it contains the finite set of instructions which are being carried in a specific order to perform the specific task. It is not the complete program or code; it is just a solution (logic) of a problem, which can be represented either as an informal description using a Flowchart or Pseudocode. Characteristics of an Algorithm The following are the characteristics of an algorithm:  Input: An algorithm has some input values. We can pass 0 or some input value to an algorithm.  Output: We will get 1 or more output at the end of an algorithm.  Unambiguity: An algorithm should be unambiguous which means that the instructions in an algorithm should be clear and simple.  Finiteness: An algorithm should have finiteness. Here, finiteness means that the algorithm should contain a limited number of instructions, i.e., the instructions should be countable.  Effectiveness: An algorithm should be effective as each instruction in an algorithm affects the overall process.  Language independent: An algorithm must be language-independent so that the instructions in an algorithm can be implemented in any of the languages with the same output. Dataflow of an Algorithm  Problem: A problem can be a real-world problem or any instance from the real-world problem for which we need to create a program or the set of instructions. The set of instructions is known as an algorithm.
  • 5.  Algorithm: An algorithm will be designed for a problem which is a step by step procedure.  Input: After designing an algorithm, the required and the desired inputs are provided to the algorithm.  Processing unit: The input will be given to the processing unit, and the processing unit will produce the desired output.  Output: The output is the outcome or the result of the program. Why do we need Algorithms? We need algorithms because of the following reasons:  Scalability: It helps us to understand the scalability. When we have a big real-world problem, we need to scale it down into small-small steps to easily analyze the problem.  Performance: The real-world is not easily broken down into smaller steps. If the problem can be easily broken into smaller steps means that the problem is feasible. Example of an Algorithm Step 1: First, we will cut the lemon into half. Step 2: Squeeze the lemon as much you can and take out its juice in a container. Step 3: Add two tablespoon sugar in it. Step 4: Stir the container until the sugar gets dissolved. Step 5: When sugar gets dissolved, add some water and ice in it. Step 6: Store the juice in a fridge for 5 to minutes. Step 7: Now, it's ready to drink. The above real-world can be directly compared to the definition of the algorithm. We cannot perform the step 3 before the step 2, we need to follow the specific order to make lemon juice. An algorithm also says that each and every instruction should be followed in a specific order to perform a specific task. The following are the steps required by the to add two numbers entered by the user. Step 1: Start
  • 6. Step 2: Declare three variables a, b, and sum. Step 3: Enter the values of a and b. Step 4: Add the values of a and b and store the result in the sum variable, i.e., sum=a+b. Step 5: Print sum Step 6: Stop Factors of an Algorithm The following are the factors that we need to consider for designing an algorithm:  Modularity: If any problem is given and we can break that problem into small-small modules or small-small steps, which is a basic definition of an algorithm, it means that this feature has been perfectly designed for the algorithm.  Correctness: The correctness of an algorithm is defined as when the given inputs produce the desired output, which means that the algorithm has been designed algorithm. The analysis of an algorithm has been done correctly.  Maintainability: Here, maintainability means that the algorithm should be designed in a very simple structured way so that when we redefine the algorithm, no major change will be done in the algorithm.  Functionality: It considers various logical steps to solve the real-world problem.  Robustness: Robustness means that how an algorithm can clearly define our problem.  User-friendly: If the algorithm is not user-friendly, then the designer will not be able to explain it to the programmer.  Simplicity: If the algorithm is simple then it is easy to understand.  Extensibility: If any other algorithm designer or programmer wants to use your algorithm then it should be extensible. Importance of Algorithms 1. Theoretical importance: When any real-world problem is given to us and we break the problem into small-small modules. To break down the problem, we should know all the theoretical aspects. 2. Practical importance: As we know that theory cannot be completed without the practical implementation. So, the importance of algorithm can be considered as both theoretical and practical. Issues of Algorithms The following are the issues that come while designing an algorithm:  How to design algorithms: As we know that an algorithm is a step-by-step procedure so we must follow some steps to design an algorithm.
  • 7.  How to analyze algorithm efficiency Time Complexity of Sorting Algorithms We might have come across various instances where we need to process the data in a specific format without taking any further delay and the same in case of unsorted data processed with higher speed so that results could be put to some use. In such instances, we use sorting algorithms so that the desired efficiency is achieved. In this article, we will discuss various types of sorting algorithms with higher emphasis on time complexities. But, before moving any further, let's understand what complexity is and what's so important to talk about it. Complexity Complexity has no formal definition at all. It just defines the rate of efficiency at which a task is executed. In data structures and algorithms, there are two types of complexities that determine the efficiency of an algorithm. They are: Space Complexity: Space complexity is the total memory consumed by the program for its execution. Time Complexity: It is defined as the times in number instruction, in particular, is expected to execute rather than the total time is taken. Since time is a dependent phenomenon, time complexity may vary on some external factors like processor speed, the compiler used, etc. In computer science, the time complexity of an algorithm is expressed in big O notation. Let's discuss some time complexities. O(1): This denotes the constant time. 0(1) usually means that an algorithm will have constant time regardless of the input size. Hash Maps are perfect examples of constant time. O(log n): This denotes logarithmic time. O(log n) means to decrease with each instance for the operations. Binary search trees are the best examples of logarithmic time.
  • 8. O(n): This denotes linear time. O(n) means that the performance is directly proportional to the input size. In simple terms, the number of inputs and the time taken to execute those inputs will be proportional or the same. Linear search in arrays is the best example of linear time complexity. The Data Type is basically a type of data that can be used in different computer program. It signifies the type like integer, float etc, the space like integer will take 4-bytes, character will take 1-byte of space etc. The abstract datatype is special kind of datatype, whose behavior is defined by a set of values and set of operations. The keyword “Abstract” is used as we can use these datatypes, we can perform different operations. But how those operations are working that is totally hidden from the user. The ADT is made of with primitive datatypes, but operation logics are hidden. Some examples of ADT are Stack, Queue, List etc. Let us see some operations of those mentioned ADT − Stack − isFull(), This is used to check whether stack is full or not isEmpry(), This is used to check whether stack is empty or not push(x), This is used to push x into the stack pop(), This is used to delete one element from top of the stack peek(), This is used to get the top most element of the stack size(), this function is used to get number of elements present into the stack Queue − isFull(), This is used to check whether queue is full or not isEmpry(), This is used to check whether queue is empty or not
  • 9. insert(x), This is used to add x into the queue at the rear end delete(), This is used to delete one element from the front end of the queue size(), this function is used to get number of elements present into the queue List − size(), this function is used to get number of elements present into the list insert(x), this function is used to insert one element into the list remove(x), this function is used to remove given element from the list get(i), this function is used to get element at position i replace(x, y), this function is used to replace x with y value O(n2): This denotes quadratic time. O(n2) means that the performance is directly proportional to the square of the input taken. In simple, the time taken for execution will take square times the input size. Nested loops are perfect examples of quadratic time complexity. Array in Data Structure Arrays are defined as the collection of similar types of data items stored at contiguous memory locations. It is one of the simplest data structures where each data element can be randomly accessed by using its index number. In C programming, they are the derived data types that can store the primitive type of data such as int, char, double, float, etc. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define a different variable for the marks in different subjects. Instead, we can define an array that can store the marks in each subject at the contiguous memory locations. Properties of array There are some of the properties of an array that are listed as follows -  Each element in an array is of the same data type and carries the same size that is 4 bytes.  Elements in the array are stored at contiguous memory locations from which the first element is stored at the smallest memory location.  Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
  • 10. Representation of an array  We can represent an array in various ways in different programming languages. As an illustration, let's see the declaration of array in C language – We can represent an array in various ways in different programming languages. As an illustration, let's see the declaration of array in C language - x As per the above illustration, there are some of the following important points -  Index starts with 0.  The array's length is 10, which means we can store 10 elements.  Each element in the array can be accessed via its index. Why are arrays required? Arrays are useful because -  Sorting and searching a value in an array is easier.  Arrays are best to process multiple values quickly and easily.  Arrays are good for storing multiple values in a single variable - In computer programming, most cases require storing a large number of data of a similar type. To store such an amount of data, we need to define a large number of variables. It would be
  • 11. very difficult to remember the names of all the variables while writing the programs. Instead of naming all the variables with a different name, it is better to define an array and store all the elements into it. Memory allocation of an array As stated above, all the data elements of an array are stored at contiguous locations in the main memory. The name of the array represents the base address or the address of the first element in the main memory. Each element of the array is represented by proper indexing. We can define the indexing of an array in the below ways - 1. 0 (zero-based indexing): The first element of the array will be arr[0]. 2. 1 (one-based indexing): The first element of the array will be arr[1]. 3. n (n - based indexing): The first element of the array can reside at any random index number. In the above image, we have shown the memory allocation of an array arr of size 5. The array follows a 0-based indexing approach. The base address of the array is 100 bytes. It is the address of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each element will take 4 bytes in the memory. How to access an element from the array? We required the information given below to access any random element from the array -  Base Address of the array.  Size of an element in bytes.  Type of indexing, array follows. The formula to calculate the address to access an array element - 1. Byte address of element A[i] = base address + size * ( i - first index)
  • 12. Here, size represents the memory taken by the primitive data types. As an instance, int takes 2 bytes, float takes 4 bytes of memory space in C programming. We can understand it with the help of an example - Suppose an array, A[-10 ..... +2 ] having Base address (BA) = 999 and size of an element = 2 bytes, find the location of A[-1]. L(A[-1]) = 999 + 2 x [(-1) - (-10)] = 999 + 18 = 1017 Stack in Data Structure A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has one end, whereas the Queue has two ends (front and rear). It contains only one pointer top pointer pointing to the topmost element of the stack. Whenever an element is added in the stack, it is added on the top of the stack, and the element can be deleted only from the stack. In other words, a stack can be defined as a container in which insertion and deletion can be done from the one end known as the top of the stack. Some key points related to stack  It is called as stack because it behaves like a real-world stack, piles of books, etc.  A Stack is an abstract data type with a pre-defined capacity, which means that it can store the elements of a limited size.  It is a data structure that follows some order to insert and delete the elements, and that order can be LIFO or FILO. Working of Stack Stack works on the LIFO pattern. As we can observe in the below figure there are five memory blocks in the stack; therefore, the size of the stack is 5. Suppose we want to store the elements in a stack and let's assume that stack is empty. We have taken the stack of size 5 as shown below in which we are pushing the elements one by one until the stack becomes full.
  • 13. Since our stack is full as the size of the stack is 5. In the above cases, we can observe that it goes from the top to the bottom when we were entering the new element in the stack. The stack gets filled up from the bottom to the top. When we perform the delete operation on the stack, there is only one way for entry and exit as the other end is closed. It follows the LIFO pattern, which means that the value entered first will be removed last. In the above case, the value 5 is entered first, so it will be removed only after the deletion of all the other elements. Standard Stack Operations The following are some common operations implemented on the stack:  push(): When we insert an element in a stack then the operation is known as a push. If the stack is full then the overflow condition occurs.  pop(): When we delete an element from the stack, the operation is known as a pop. If the stack is empty means that no element exists in the stack, this state is known as an underflow state.  isEmpty(): It determines whether the stack is empty or not.  isFull(): It determines whether the stack is full or not.'  peek(): It returns the element at the given position.  count(): It returns the total number of elements available in a stack.  change(): It changes the element at the given position.  display(): It prints all the elements available in the stack. PUSH operation The steps involved in the PUSH operation is given below:
  • 14.  Before inserting an element in a stack, we check whether the stack is full.  If we try to insert the element in a stack, and the stack is full, then the overflow condition occurs.  When we initialize a stack, we set the value of top as -1 to check that the stack is empty.  When the new element is pushed in a stack, first, the value of the top gets incremented, i.e., top=top+1, and the element will be placed at the new position of the top.  The elements will be inserted until we reach the max size of the stack. POP operation The steps involved in the POP operation is given below:  Before deleting the element from the stack, we check whether the stack is empty.  If we try to delete the element from the empty stack, then the underflow condition occurs.  If the stack is not empty, we first access the element which is pointed by the top  Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
  • 15. Applications of Stack The following are the applications of the stack:  Balancing of symbols: Stack is used for balancing a symbol. For example, we have the following program: 1. int main() 2. { 3. cout<<"Hello"; 4. cout<<"javaTpoint"; 5. } As we know, each program has an opening and closing braces; when the opening braces come, we push the braces in a stack, and when the closing braces appear, we pop the opening braces from the stack. Therefore, the net value comes out to be zero. If any symbol is left in the stack, it means that some syntax occurs in a program.  String reversal: Stack is also used for reversing a string. For example, we want to reverse a "javaTpoint" string, so we can achieve this with the help of a stack. First, we push all the characters of the string in a stack until we reach the null character. After pushing all the characters, we start taking out the character one by one until we reach the bottom of the stack.  UNDO/REDO: It can also be used for performing UNDO/REDO operations. For example, we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text
  • 16. written in an editor is abc. So, there are three states, a, ab, and abc, which are stored in a stack. There would be two stacks in which one stack shows UNDO state, and the other shows REDO state. If we want to perform UNDO operation, and want to achieve 'ab' state, then we implement pop operation.  Recursion: The recursion means that the function is calling itself again. To maintain the previous states, the compiler creates a system stack in which all the previous records of the function are maintained.  DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the stack data structure.  Backtracking: Suppose we have to create a path to solve a maze problem. If we are moving in a particular path, and we realize that we come on the wrong way. In order to come at the beginning of the path to create a new path, we have to use the stack data structure.  Expression conversion: Stack can also be used for expression conversion. This is one of the most important applications of stack. The list of the expression conversion is given below: Notation in Stack 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.
  • 17. 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.
  • 18. 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 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 Conversion of Prefix to Postfix expression Before understanding the conversion of prefix to postfix conversion, we should know about the prefix and postfix expressions separately. What is Prefix conversion? An infix expression is an expression in which the operators are written between the two operands. If we move the operator before the operands then it is known as a prefix expression. In other words, prefix expression can be defined as an expression in which all the operators precede the two operands. For example: If the infix expression is given as: A + B * C
  • 19. As we know that the multiplication operator * has a higher precedence than the addition operator. First, multiplication operator will move before operand B shown as below: A + * B C Once the multiplication operator is moved before 'B' operand, addition operator will move before the operand 'A' shown as below: + A * B C Evaluation of Prefix Expression using Stack Step 1: Initialize a pointer 'S' pointing to the end of the expression. Step 2: If the symbol pointed by 'S' is an operand then push it into the stack. Step 3: If the symbol pointed by 'S' is an operator then pop two operands from the stack. Perform the operation on these two operands and stores the result into the stack. Step 4: Decrement the pointer 'S' by 1 and move to step 2 as long as the symbols left in the expression. Step 5: The final result is stored at the top of the stack and return it. Step 6: End Let's understand the evaluation of prefix expression through an example. Expression: +, -, *, 2, 2, /, 16, 8, 5 First, we will reverse the expression given above. Expression: 5, 8, 16, /, 2, 2, *, -, + We will use the stack data structure to evaluate the prefix expression. Symbol Scanned Stack 5 5 8 5, 8
  • 20. 16 5, 8, 16 / 5, 2 2 5, 2, 2 2 5, 2, 2, 2 * 5, 2, 4 - 5, 2 + 7 The final result of the above expression is 7. What is Postfix expression? If we move the operators after the operands then it is known as a postfix expression. In other words, postfix expression can be defined as an expression in which all the operators are present after the operands. For example: If the infix expression is A + B * C As we know that the multiplication operator has a higher precedence than the addition operator, so multiplication operator will move after the operands B and C shown as below: A + B C * Once the multiplication operator is moved after the operand C, then the addition operator will come after the multiplication operator shown as below: A B C * + Evaluation of Postfix expression using Stack Algorithm for the evaluation of postfix expression using stack: Step 1: Create an empty stack used for storing the operands.
  • 21. Step 2: Scan each element of an expression one be one and do the following: o If the element is an operand then push it into the stack. o If the element is an operator then pop two operands from the stack. Perform operation on these operands. Push the final result into the stack. Step 3: When the expression is scanned completely, the value available in the stack would be the final output of the given expression. Let's understand the evaluation of postfix expression using stack through an example. If the expression is: 5, 6, 2, +, *, 12, 4, /, - Symbol Scanned Stack 5 5 6 5, 6 2 5, 6, 2 + 5, 8 * 40 12 40, 12 4 40, 12, 4 / 40, 3 - 37 The result of the above expression is 37. Conversion of Prefix to Postfix Expression Here, we will see the conversion of prefix to postfix expression using a stack data structure. Rules for prefix to postfix expression using stack data structure:
  • 22. o Scan the prefix expression from right to left, i.e., reverse. o If the incoming symbol is an operand then push it into the stack. o If the incoming symbol is an operator then pop two operands from the stack. Once the operands are popped out from the stack, we add the incoming symbol after the operands. When the operator is added after the operands, then the expression is pushed back into the stack. o Once the whole expression is scanned, pop and print the postfix expression from the stack. f the expression is: * - A / B C - / A K L Symbols to be scanned Action Stack Description L Push L into the stack L K Push K into the stack L, K A Push A into the stack L, K, A / Pop A from the stack Pop K from the stack Push A K / into the stack L, A K / Pop two operands from the stack, i.e., A an K. Add '/' operator after K operand, i.e., AK Push AK/ into the stack. - Pop A K / and L from the stack. Push (A K / L -) into the stack A K / L - Pop two operands from the stack, i.e., AK and L. Add '-' operator after 'L' operand. C Push C into the stack AK/L-, C B Push B into the stack AK/L-, C, B / Pop B and C from the stack. Push BC/ into the stack. AK/L-, BC/ Pop two operands from the stack, i.e., B an C. Add '/' operator after C operator, i.e., BC Push BC/ into the stack.
  • 23. A Push A into the stack AK/L-, BC/, A - Pop BC/ and A from the stack. Push ABC/- into the stack. AK/L-, ABC/- Pop two operands from the stack, i.e., A an BC/. Add '-' operator after '/'. * Pop ABC/- and AK/L- from the stack. Push ABC/AK/L-* into the stack. ABC/- AK/L-* Pop two operands from the stack, i.e., ABC/ , and AK/L- . Add '*' operator after L and ' operator, i.e., ABC/-AK/L-*. Conversion of Postfix to Prefix expression What is Postfix expression? A postfix expression is said to be an expression in which the operator appears after the operands. It can be written as: (operand) (operand) (operator) For example: If the expression is: (A+B) * (C+D) Firstly, operator precedence rules will be applied to the above expression. Since the parenthesis has higher precedence than the multiplication operator; therefore '+' will be resolved first, and the + operator will come after AB and CD shown as below: (AB+) * (CD+) Now, the multiplication operator will move after CD+ shown as below: AB+ CD+* What is Prefix Expression? A prefix expression is said to be an expression in which the operator appears before the operands.
  • 24. For example: If the expression is given as: (A+B) * (C+D) Firstly, operator precedence rules will be applied to the above expression. Since the parenthesis has higher precedence than the multiplication operator; therefore, the '+' operator will be resolved first, and the '+' operator will move before the operands AB and CD shown as below: (+AB) * (+CD) Now, the multiplication operator will move before the +AB shown as below: *+AB+CD Conversion of Postfix to Prefix expression There are two ways of converting a postfix into a prefix expression: 1. Conversion of Postfix to Prefix expression manually. 2. Conversion of Postfix to Prefix expression using stack. Pointer Pointer is used to points the address of the value stored anywhere in the computer memory. To obtain the value stored at the location is known as dereferencing the pointer. Pointer improves the performance for repetitive process such as:  Traversing String  Lookup Tables  Control Tables  Tree Structures Pointer Details
  • 25.  Pointer arithmetic: There are four arithmetic operators that can be used in pointers: ++, --, +, -  Array of pointers: You can define arrays to hold a number of pointers.  Pointer to pointer: C allows you to have pointer on a pointer and so on.  Passing pointers to functions in C: Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function.  Return pointer from functions in C: C allows a function to return a pointer to the local variable, static variable and dynamically allocated memory as well. Program Pointer 1. #include <stdio.h> 2. 3. int main( ) 4. { 5. int a = 5; 6. int *b; 7. b = &a; 8. 9. printf ("value of a = %dn", a); 10. printf ("value of a = %dn", *(&a)); 11. printf ("value of a = %dn", *b); 12. printf ("address of a = %un", &a);
  • 26. 13. printf ("address of a = %dn", b); 14. printf ("address of b = %un", &b); 15. printf ("value of b = address of a = %u", b); 16. return 0; 17. } Output 1. value of a = 5 2. value of a = 5 3. address of a = 3010494292 4. address of a = - 1284473004 5. address of b = 3010494296 6. value of b = address of a = 3010494292 String in Data Structure String is an array of characters and terminated by a null character (0). The null character is not placed by the user, the compiler places it at the end of string automatically. The difference between an array and a string is that the compiler does not place null character at the end of array while in string, compiler places null character. Here is the syntax of string in C language, char myStr[size]; Here, myStr: The string size: Set the size of string Initialize string in C language like show below − char myStr[size] = “string”; char myStr[size] = { ‘s’,’t’,’r’,’i’,’n’,’g’,’0’ };
  • 27. The following table displays functions of string in C language. Function Purposes strcpy(s1, s2) Copies string s2 into string s2 strcat(s1, s2) Concatenates s2 onto end of s1 strlen(s1) Returns the length of string s1 strcmp(s1, s2) Returns 0 when s1 and s2 are same Greater than 0 when ASCII value of s1 is greater than s2 Lesser than 0 when ASCII value of s1 is lesser than s2 strchr(s1, ch) Returns the pointer to the first occurence of character ch in string s1 strstr(s1, s2) Returns the pointer to the first occurence of string s2 in string s1 List in Data Structure The list can be defined as an abstract data type in which the elements are stored in an ordered manner for easier and efficient retrieval of the elements. List Data Structure allows repetition that means a single piece of data can occur more than once in a list. In the case of multiple entries of the same data, each entry of that repeating data is considered as a distinct item or entry. It is very much similar to the array but the major difference between the array and the list data structure is that array stores only homogenous data in them whereas the list (in some programming languages) can store heterogeneous data items in its object. List Data Structure is also known as a sequence. The list can be called Dynamic size arrays, which means their size increased as we go on adding data in them and we need not to pre-define a static size for the list. For example, numbers = [ 1, 2, 3, 4, 5] In this example, 'numbers' is the name of the List Data Structure object and it has five items stored in it. In the object named numbers, we have stored all the elements of numeric type. In the list, the indexing starts from zero, which means if we want to access or retrieve the first element of this list then we need to use index zero and similarly whenever we want to access any element from this list named numbers. In other words, we can say that element 1 is on the index 0 and element 2 is on index 1 and similarly for further all elements.
  • 28. Mixed_data = [205, 'Nirnay', 8.56] In this second example, mixed_data is the name of the list object that stores the data of different types. In the mixed_data list, we have stored data of three types, first one is the integer type which is id '205', after the integer data we have stored a string type data having the value 'Nirnay' stored at index 1 and at last the index value 2, we have stored a float type data having the value '8.56'. To access the elements of the mixed_data list, we need to follow the same approach as defined in the previous example. And we can add more data to these defined List objects and that will get appended at the last of the list. For example, if we add another data in the mixed_data list, it will get appended after the float value object having value '8.56'. And we can add repeating values to these list-objects. Queue: Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first. A real-world example of queue can be a single-lane one-way road, where the vehicle enters first, exits first. More real-world examples can be seen as queues at the ticket windows and bus- stops. 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.
  • 29. 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.  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
  • 30. begin procedure isfull if rear equals to MAXSIZE return true else return false endif end procedure Example bool isfull() { if(rear == MAXSIZE - 1) return true; else return false; } isempty() Algorithm of isempty() function − Algorithm begin procedure isempty if front is less than MIN OR front is greater than rear return true else return false endif end procedure If the value of front is less than MIN or 0, it tells that the queue is not yet initialized, hence empty. Here's the C programming code − Example bool isempty() { if(front < 0 || front > rear) return true; else return false; } Enqueue Operation
  • 31. 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. Queue Enqueue Algorithm for enqueue operation procedure enqueue(data) if queue is full return overflow endif rear ← rear + 1 queue[rear] ← data return true end procedure Implementation of enqueue() in C programming language − Example 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.
  • 32.  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 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; }