C++ Unit-2
C++ Unit-2
1
ADVANTAGES OF DATA STRUCTURES
2
CLASSIFICATIONS (PRIMITIVE & NON PRIMITIVE),
3
Data Structure
Primitive Non-Primitive
Integer
Linear Non Linear
Float
Character
Pointer
5
CLASSIFICATION OF DATA STRUCTURES
Types of Data Structures Based on relationship between data elements
The below categories is under Non-Primitive Data Structures.
1. Linear data structure
2. Non-Linear data structure
6
CLASSIFICATION OF DATA STRUCTURE
7
CLASSIFICATION OF DATA STRUCTURES
8
NON-HOMOGENEOUS/ HETEROGENEOUS
Homogeneous data: Homogeneous data structures are those data structures that contain
only similar type of data e.g. like a data structure containing only integer or float values.
The simplest example of such type of data structures is an Array.
9
Data Structures may also be classified as
1. Static Data Structures
2. Dynamic Data Structures
Static Data Structures :In Static data structure the size of the structure is fixed. The content
of the data structure can be modified but without changing the memory space allocated to it.
Example of Static Data Structures: Array
Dynamic Data Structures : In Dynamic data structure the size of the structure in not fixed
and can be modified during the operations performed on it. Dynamic data structures are
designed to facilitate change of data structures in the run time.
Example of Dynamic Data Structures: Linked List
10
OPERATIONS ON PRIMITIVE DATA STRUCTURES
11
OPERATIONS ON NON-PRIMITIVE DATA STRUCTURES
Traversal
Insertion
Deletion
Sorting
Searching
Merging
12
ARRAYS
Array is the collection of similar data types Arrays can be single or multidimensional. The number
or collection of similar entity stored in of subscript or index determines the dimensions of
contiguous memory location. the array.
Array of character is a string. Each data An array of one dimension is known as a one-
item of an array is called an element. And dimensional array or 1-D array, while an array of
each element is unique and located in two dimensions is known as a two-
separated memory location. Each of dimensional array or 2-D array.
elements of an array share a variable but
each element having different index no. NOTE:
known as subscript. • Arrays index will starts with zero
• arrays will occupy contigeous memory locations.
TYPES OF ARRAYS
17
COURSE OUTCOMES:
18
PROGRAM TO DELETE AN ELEMENT FROM ARRAY IN C
19
ARRAYS – 2D ARRAYS
NOTE:
• Arrays index will starts with zero
• arrays will occupy contigeous memory locations.
TWO DIMENSIONAL ARRAYS
Two dimensional array is known as matrix. // Different ways to initialize two-
The array declaration in both the array i.e. in
dimensional array
single dimensional array single subscript is
used and in two dimensional array two int x[5][5]={4,6,8,3,5,7}
subscripts are is used. int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
Syntax int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
variable_name[row][column]; int c[2][3] = {1, 3, 0, -1, 5, 9};
Eg: int x[3][4];
ARRAYS – 2D ARRAYS
There are several string library functions used It accepts a single argument which is
to manipulate string and the prototypes for pointer to the first character of the
these functions are in header file “string.h”. string.
Several string functions are Ex: strlen(“suresh”);
strlen() It return the value 6.
This function return the length of the string. i.e. void main()
the number of characters in the string excluding {
the terminating NULL character. char str[50];
print(”Enter a string:”);
Syntax: strlen(string);
gets(str);
printf(“Length of the string is %d\
n”,strlen(str));
}
OVERVIEW OF STRUCTURES UNION
Structure : It is the collection of dissimilar data types or heterogeneous data types
grouped together. It means the data types may or may not be of same type.
Syntax : struct tag_name
{ Data type member1;
Data type member2;
Data type member3;
……… ………
Data type member n;
};
INITIALIZATION OF STRUCTURE VARIABLE
SC HOOL OF C S A , R E VA U n i v e r s i t y
Deep a B G
STACK
Stack is a special type of data structure where elements are inserted and deleted from
the same end.
It is named stack as it behaves like a real-world stack, for example – a deck
of cards or a pile of plates, etc.
For example, we can place or remove a card or plate from the top of the
stack only. Likewise, Stack ADT allows all data operations at one end only. At
any given time, we can only access the top element of a stack.
34
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed
(inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation
and removal operation is called POP operation.
Stack Representation
35
OPERATIONS ON STACK
36
PUSH OPERATION
The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps −
37
PUSH OPERATION CONTD..
If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically
38
Programming Logic
39
POP OPERATION
The procedure of removing element from the top of the stack is called pop
operation.
Only one element can be deleted from stack at a time and element has to be deleted
only from the top of the stack.
When elements are being deleted, there is a possibility of stack being empty.
When stack is empty, it is not possible to delete any element.
Trying to delete an element from an empty stack results in stack underflow.
After every pop operation, the value of TOP is decremented by one.
40
POP OPERATION
A Pop operation may involve the following steps −
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error and exit.
• Step 3 − If the stack is not empty, accesses the data element at
which top is pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.
41
PROGRAMMING LOGIC
{
data = stack[top];
top = top - 1;
return data;
}
else
{
cout<<"Could not retrieve data, Stack is empty”<<“\n");
}
}
42
Peek operation
At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always represents
the top of the stack, hence named top. The top pointer provides top value of the stack without actually
removing it.
Example
int peek()
{
return stack[top];
}
43
bool isfull()
{
isfull() if(top == MAXSIZE)
return true;
Else
return false; }
isempty()
Implementation of isempty() function in C programming language is slightly different. We initialize top at -1, as
the index in array starts from 0. So we check if the top is below zero or -1 to determine if the stack is empty.
bool isempty()
{
if(top == -1)
return true;
else
return false;
} 44
STACK APPLICATIONS: INFIX TO POSTFIX CONVERSION
CONTD..
Infix Expression
It follows the scheme of <operand><operator><operand> i.e. an <operator> is
preceded and succeeded by an <operand>. Such an expression is termed infix
expression.
E.g., A+B
Postfix Expression
It follows the scheme of <operand><operand><operator> i.e. an <operator> is
succeeded by both the <operand>.
E.g., AB+
45
ALGORITHM TO CONVERT INFIX TO POSTFIX
1. Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Y.
3. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the same precedence as or higher precedence
than operator.
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left parenthesis is encountered.
8. END.
46
EXAMPLE:
47
PROGRAM to convert infix to postfix expression
48
LECTURE 7
50
POSTFIX EXPRESSION EVALUATION USING STACK DATA
STRUCTURE
1. A postfix expression can be evaluated using the Stack data structure. To evaluate a
postfix expression using Stack data structure we can use the following steps...
2. Read all the symbols one by one from left to right in the given Postfix Expression
3. If the reading symbol is operand, then push it on to the Stack.
4. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop
operations and store the two popped operands in two different variables (operand1
and operand2). Then perform reading symbol operation using operand1 and
operand2 and push result back on to the Stack.
5. Finally! perform a pop operation and display the popped value as final result.
51
EXAMPLE:
52
EXAMPLE: CONTD..
53
54
Linear Data Structures: Queue
SC HOOL OF C S A , R E VA U n i v e r s i t y
Deep a B G
LECTURE 1
58
BASIC FEATURES OF QUEUE
1. Like stack, queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the
new element in the queue must be moved front.
4. peek( ) function is oftenly used to return the value of first element without
dequeuing it.
59
APPLICATIONS OF QUEUE
Queue, as the name suggests is used whenever we need to manage any group of objects
in an order in which the first one coming in, also gets out first while the others wait for
their turn, like in the following scenarios:
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people calling
them in an order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same
order as they arrive i.e First come first served.
60
IMPLEMENTATION OF QUEUE DATA STRUCTURE
61
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 −
1. enqueue() − add (store) an item to the queue.
2. dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient.
These are −
3. peek() − Gets the element at the front of the queue without removing it.
4. isfull() − Checks if the queue is full.
5. isempty() − Checks if the queue is empty.
62
ALGORITHM FOR 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 −
1. Step 1 − Check if the queue is full.
2. Step 2 − If the queue is full, produce overflow error and exit.
3. Step 3 − If the queue is not full, increment rear pointer to point the next empty
space.
4. Step 4 − Add data element to the queue location, where the rear is pointing.
5. Step 5 − return success.
63
64
IMPLEMENTATION OF ENQUEUE
65
ALGORITHM FOR 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 −
1. Step 1 − Check if the queue is empty.
2. Step 2 − If the queue is empty, produce underflow error and exit.
3. Step 3 − If the queue is not empty, access the data where front is pointing.
4. Step 4 − Increment front pointer to point to the next available data element.
5. Step 5 − Return success.
66
67
IMPLEMENTATION OF DEQUEUE
int dequeue()
{
if(isempty())
return 0;
int data = queue[front];
front = front + 1;
}
Return data
68
PEEK()
This function helps to see the data at the front of the queue. The algorithm of peek()
function is as follows −
69
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 −
70
ISEMPTY()
If the value of front is less than MIN or 0, it tells that the queue is not yet initialized,
hence empty.
71