Module-1_DS_2024
Module-1_DS_2024
Data structure
Primitive DS Non-Primitive DS
Integer
Integer Float
Float Character Pointer
Cont…
Non-Primitive DS
• Types of allocation
• Static Memory allocation : allocating memory at compilation time
• Dynamic memory allocation : allocating memory at execution time
Dynamic Memory Allocation Functions
allocation.
Cont..
malloc( )
● The function malloc allocates a user- specified amount of memory and
a pointer to the start of the allocated memory is returned.
● If there is insufficient memory to make the allocation, the returned
value is NULL. Malloc returns void *, so need to do typecasting.
● Syntax: data_type *x;
x= (data_type *) malloc(size);
MALLOC(pi, sizeof(int) );
MALLOC(pf, sizeof(float) );
DYNAMICALLY ALLOCATED 1D ARRAYS
int i, n, *list;
printf(“Enter the number of numbers to generate:”);
scanf(“%d”, &n);
if(n<1)
{
fprintf (stderr, “Improper value of n \n”);
exit(EXIT_FAILURE);
}
MALLOC (list, n*sizeof(int));
The programs fail only when n<1 or insufficient memory to hold the list of
numbers that are to be sorted
DYNAMICALLY ALLOCATED 2D ARRAYS
int **myArray;
myArray = make2dArray(5,10);
myArray[2][4]=6;
strcpy(personl.name, person2.name);
personl.age = person2.age;
personl.salary = person2.salary;
NOTE: Structure cannot be directly checked for equality or inequality.
if (personl == person2 )
#define FALSE 0
#define TRUE 1
int humans_equal(human_being personl, human_being person2)
{
if (strcmp(personl.name, person2.name))
return FALSE;
if (personl.age != person2.age)
return FALSE;
if (personl.salary 1= person2.salary)
return FALSE;
return TRUE;
}
Embed a structure within a structure
typedef struct {
int month;
int day;
int year;
} date; personl.dob.month = 2;
personl.dob.day = 11;
personl.dob.year = 1944;
typedef struct human_being {
char name[10];
int age;
float salary;
date dob;
};
Unions
● Continuing with our human-being example, it would be nice if we could
distinguish between males and females. In the case of males we might ask
whether they have a beard or not. In the case of females we might wish to
know the number of children they have borne. This gives rise to another
feature of C called a union.
● A union declaration is similar to a structure, but the fields of a union must
share their memory space.
● This means that only one field of the union is "active" at any given time.
Union Example
typedef struct sex_type {
enum tag_field {female, male} sex;
union {
int children;
int beard ; personl.sex_info.sex = male;
} u; personl.sex_info.u.beard = FALSE;
};
person2.sex_info.sex = female;
typedef struct human_being { person2.sex_info.u.children = 4;
char name[10];
int age;
float salary;
date dob;
sex_type sex_info;
};
human_being personl, person2;
Self-Referential Structures
• Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.
typedef struct list {
Example: char data;
list *link;
} ;
list iteml, item2, item3;
iteml.data = ‘a’;
item2.data = ‘b’;
item3.data = ‘c’;
iteml.link = item2.link = item3.link = NULL ;
item1.link = &item2;
item2.link = &item3;
Types of Self Referential Structures
• Self Referential Structure with Single Link
• Self Referential Structure with Multiple Links
Self Referential Structure with Single Link
These structures can have only one self-pointer as their member. The
following example will show us how to connect the objects of a self-
referential structure with the single link and access the corresponding
data members.
Self Referential Structure with Multiple Links
• Self referential structures with multiple links can have more than one
self-pointers. Many complicated data structures can be easily
constructed using these structures. Such structures can easily connect
to more than one node at a time. The following example shows one
such structure with more than one links.
Applications
Self referential structures are very useful in creation of other complex
data structures like:
➢ Linked Lists
➢ Stacks
➢ Queues
➢ Trees
➢ Graphs
Difference between Structure and Union
Array Operations
➢ Traversing
➢ Inserting
➢ Deleting
➢ Searching
➢ Sorting
Example for Insertion and Deletion
Sorting
Sorting refers to the operation of rearranging the elements of a list.
• Ex: suppose A is the list of n numbers. Sorting A refers to the
operation of rearranging the elements of A so they are in increasing
order, i.e., so that,
A[I] < A[2] < A[3] < ... < A[N]
For example, suppose A originally is the list
8, 4, 19, 2, 7, 13, 5, 16
After sorting, A is the list
2, 4, 5, 7, 8, 13, 16, 19
Bubble Sort
Algorithm: BUBBLE (DATA, N)
Here DATA is an array with N elements. This algorithm sorts the
elements in DATA.
• Repeat Steps 2 and 3 for K = 1 to N - 1.
• Set PTR: = 1.[Initializes pass pointer PTR.]
• Repeat while PTR ≤ N - K: [Executes pass.]
• If DATA[P TR] > DATA[P TR + 1], then:
Interchange DATA [PTR] and DATA [PTR + 1]. [End of If structure.]
• Set PTR: = PTR + 1. [End of inner loop.]
[End of Step 1 outer loop.]
Exit
Searching
Searching refers to the operation of finding the location LOC of ITEM in DATA, or
printing some message that ITEM does not appear there.
Algorithm: (Linear Search) LINEAR (DATA, N, ITEM, LOC)
Here DATA is a linear array with N elements, and ITEM is a given item of information.
This algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search is
unsuccessful.
[Insert ITEM at the end of DATA.] Set DATA [N + 1]: = ITEM.
[Initialize counter.] Set LOC: = l.
[Search for ITEM.]
Repeat while DATA [LOC] ≠ ITEM: Set LOC:= LOC + 1.
[End of loop.]
[Successful?] If LOC = N + 1, then: Set LOC:= 0
Exit.
Binary Search
Brute-force algorithm
Step 1 Align pattern at beginning of text
Step 2 Moving from left to right, compare each character of
pattern to the corresponding character in text until
• all characters are found to match (successful search); or
• a mismatch is detected
Step 3 While pattern is not found and the text is not yet
exhausted, realign pattern one position to the right and
repeat Step 2
END of MODULE 1
Happy Learning
STACKS
INTRODUCT
ION
• The linear lists and linear arrays allows one to insert
and delete elements at any place in the list- at the
beginning, at the end or in the middle
• There are certain frequent situations when one
wants to restricts insertions and deletions so that
they can take place only at the beginning or the
end of the list, not in the middle
• They are STACKS and QUEUES
STACKS
• Stack is a linear list in which addition and deletion of
elements are restricted to one end called the top.
• A linear list is a list in which each element has unique
successor.
• A linear list may be a restricted list or a general list.
• Stack is also called as
• LIFO Data structure
• Push down list
Stack Operations
• PUSH – Used to insert an element into Stack.
• POP – Used to delete an element from Stack.
• Stack top – used to copy the item at the top of
Stack but does not delete it.
Underflow and Overflow
• Underflow is a condition occurs if we try to POP
item from the empty STACK
• Overflow is a condition occurs if we try to PUSH an
ITEM to the STACK which is already full
STAC
E D C B A
K STACK OVERFLOW
FULL
<--TOP
POP
D <--TOP
STACK
EMPTY
STACK UNDERFLOW
Array representation of Stack
• Array can be used as home to the stack
• Data structure
#define MAX STK 25
typedef struct {
int top;
char item[MAXSTK];
}STACK;
STACK s;
s.top= -1;
A B C D
top
Stack after – PUSH( ‘A’), PUSH( ‘B’), PUSH( ‘C’), PUSH( ‘D’)
PUSH(STACK, TOP, MAXSTK, ITEM)
This procedure pushes an ITEM onto a stack
1.[ Stack already filled? ]
If TOP = MAXSTK, then: print: OVERFLOW, and
return
2. Set TOP := TOP + 1 [ Increases TOP BBY 1]
3.Set STACK[ TOP ] := ITEM [ Inserts ITEM in new TOP
position ]
4. Return
POP(STACK, TOP, ITEM)
This procedure deletes the top element of STACK
and assigns it to the variable ITEM
1. [ Stack has an item to be removed? ]
If TOP = 0, then: Print : UNDERFLOW, and Return
2.Set ITEM := STACK[ TOP ]. [ Assigns TOP element to
ITEM ]
3. Set TOP := TOP – 1. [ Decreases TOP by 1 ]
4. Return
Stack representation using arrays
in C
#define MAXSTK 10
typedef struct {
int item[MAXSTK];
int top;
}STACK;
STACK s;
s.top = -1;
#define MAX 25
Stacks using dynamic typedef struct {
int key;
arrays /*other fields*/
}Element;
Element * stack;
int top= -1;
capacity = 1;
stack = (Element *) malloc (sizeof (*stack));
int IsFull( ) {
if ( top >= capacity – 1)
return 1;
return 0;
}
Void Push(Element item)
{
If(IsFull( ))
Stackfull( );
Top++;
* stack=item;
return;
}
Stackfull( )
{
Stack=realloc(2*capacity*size of (*stack));
Capacity*=2;
}
int Isempty( ){
If(top <0)
return 1;
return 0;
}
Element Pop( )
{
Element x;
If(!Is empty(s)
{
X=*stack;
Stack--;
return x;
}
}
Array doubling
void stackFull()
{
realloc(s , 2*capacity*sizeof(*s));
capacity * = 2;
}
Stack Applications
• Postponing data usage
• Reversing Data
• Parsing Data
• Backtracking Steps.
Postponing data usage
• Note
• The order of operators and operands in an INFIX expression does not uniquely
determine the order in which operations to be performed
• In POLISH and REVERSE POLISH notation the order in which the operations to be
preformed is completely determined by the position of the operators and the
operands in the expression
• No parenthesis required to determine the order
• Computer evaluates arithmetic expressions in INFIX notation in two steps
• 1) Convert INFIX expression to POSTIX
• 2) Evaluate the POSTFIX expression
Converting infix to postfix and Prefix -
Examples
INFIX
1. A+B*C : A+[BC*] ABC*+ is
POSTFIX
A+[*BC] +A*BC is PREFIX
2 (A+B)*C : [AB+]*C AB+C* is
3 A$B*C-D+E/F/G+H: [AB$]*C-D+E/F/G+H
POSTFIX
(Converting to postfix ) [AB$C*]-D+[EF/G/]+H
[+AB]*C *+ABC is PREFIX
AB$C*D-EF/G/+H+ is POSTFIX
(Converting to prefix) [$AB]*C-D+E/F/G+H
[*$ABC]-D+[//EFG]+H
++-*$ABCD//EFGH is PREFIX
Converting infix to postfix and Prefix -
INFIX toExamples
POSTFIX Conversion
Given Infix Expression: ((A+B)*C-(D-E))$(F+G)
([AB+]*C-[DE-])$[FG+]
([AB+C*]-[DE-])$[FG+]
[AB+C*DE--]$[FG+]
AB+C*DE--FG+$ is Post expression
INFIX to PREFIX Conversion
Given Infix Expression: ((A+B)*C-(D-E))$(F+G)
([+AB]*C-[-DE])$[+FG]
([*+ABC]-[DE-])$[+FG]
[-*+ABC-DE]$[+FG]
$-*+ABC-DE+FG is Prefix expression
Evaluation of postfix
expression
To evaluate postfix expression, create an empty stack
• Scan from left to right to get a token
• If token is operand place on the stack
• If token is an operator remove two operands from the
stack
• Perform the operation on that operands corresponding
to the operator
• Result is placed back on the stack
• Continue the procedure until we reach end of the
expression
• Remove the answer from the stack.
Algorithm to evaluate POSTFIX expression
• EVALUATE (P)
This algorithm finds the VALUE of an arithmetic expression P written in postfix
notation
1. Append a right parenthesis “)” at the end of P.[this acts as a sentinel]
2. Scan P from left to right and repeat Steps 3 and 4 for each element of P
until the sentinel “)” is encountered
3. If an operand is encountered, place it on to STACK
4. If an operator is encountered, then,
(a) Remove the two top elements of STACK, where A is the top element and B is the next-to-top
element
(b) Evaluate B operator A
(c) Place the result of (b) back on stack
[End of If structure]
[End of Step 2 loop]
5. Set VALUE equal to the top element on STACK
6. Exit
Evaluating Given Postfix Expression :
Example: 6 2/ 3– 42*+
Token Stack top
[0] [2]
[1]
Initially -1
6 6 0
2 6 2 1
/ 3 0
3 3 3 1
- 0 0
4 0 4 1
2 0 4 2 2
* 0 8 1
+ 8 0
Postfix
Evaluation Postfix expression
62/3–42*+
stack
Postfix Expression
2/3–42*+
Token
Operand,
6 PUSH onto
stack
stack
Postfix Expression
2/3–42*+
6
stac
k
Postfix Expression
/3–42*+
Token
Operand,
2 PUSH onto
stack
6
stack
Postfix Expression
/3–42*+
2
6
stac
k
Postfix Expression
3–42*+
Token
Operator, POP
/ 2 top elements
from the stack
2
and store it in
6 opnd2 and
opnd1
stack
Postfix Expression
3–42*+
opnd1 opnd2
6 2
stack
Postfix Expression
3–42*+
Evaluate
opnd1 opnd2
opnd1
6 2 operator
opnd2
stac
k
Postfix Expression
3–42*+
Postfix Expression
3–42*+
3
stack
Postfix Expression
–42*+
Token
Operand,
3 PUSH onto
stack
3
stack
Postfix Expression
–42*+
3
3
stac
k
Postfix Expression
42*+
Token
Operator, POP
- 2 top elements
from the stack
3
and store it in
3 opnd2 and
opnd1
stack
Postfix Expression
42*+
Evaluate
opnd1 opnd2
opnd1
3 3 operator
opnd2
stac
k
Postfix Expression
42*+
0
stack
Postfix Expression
2*+
Token
Operand,
4 PUSH onto
stack
0
stac
k
Postfix Expression
2*+
4
0
stack
Postfix Expression
*+
Token
Operand,
2 PUSH onto
stack
4
0
stac
k
Postfix Expression
*+
2
4
0
stack
Postfix Expression
+
Token
Operator, POP
2 * 2 top elements
from the stack
4
and store it in
0 opnd2 and
opnd1
stac
k
Postfix Expression
+
Evaluate
opnd1 opnd2
opnd1
4 2 operator
opnd2
0
stac
k
Postfix Expression
+
Postfix Expression
+
8
0
stack
Postfix Expression
Token
Operator, POP
+ 2 top elements
from the stack
8
and store it in
0 opnd2 and
opnd1
stac
k
Postfix Expression
Evaluate
opnd1 opnd2
opnd1
0 8 operator
opnd2
stack
Postfix Expression
Postfix Expression
8
Infix to Postfix -Conversion process
• Since the order of operands in the infix and postfix expression is same
,Scan the input infix expression from left to right
• During the scan ,operands are passed directly to the postfix expression
as they are encountered.
• When the operators are encountered it is placed in the postfix expression
depending on its precedence
• To get the higher precedence first in the postfix expression, we save the operators
until we know their correct placement. To do this we follow the following
procedure
• Check the precedence of the incoming operator with the stack top.
if precedence of incoming operator is not higher than the operator at the stack top repeatedly pop the stack and place the
popped item to the postfix expression.
• place incoming operator on the stack.
• Once you reach end of infix expression repeatedly pop the stack and
place the popped item to the postfix expression till stack is empty
• In a parenthesized infix expression the expression
inside the parenthesis should be converted first.
• Hence we stack the operators until we reach the
right parenthesis
• As we encounter left parenthesis during scanning,
we must place it on the stack what ever may be
the stack top. Once left parenthesis becomes the
stack top, what ever may be the operators other
than the right parenthesis ,the operator should be
placed on the stack
• Hence left parenthesis need to behave like high
precedence when it is out from the stack and low
precedence operator when it is on the stack.
Algorithm converts INFIX expression Q into POSTFIX expression P
1 push “(“ onto STACK, and append “)” to the end of Q
2 scan Q left to right and repeat Steps 3 to 6 for each element of Q until the
STACK is empty
3 If an operand is encountered place it in the POSTFIX expression P
4 If an left parenthesis is encountered, push it on to the STACK
5 If an operator is encountered, call it as incoming operator, then:
a) Repeatedly pop from the STACK and place it in the P which has the same precedence or higher
precedence than the incoming operator
b) b) Place the incoming operator to the STACK
[End of IF]
6 If a right parentheses is encountered
a)Repeatedly pop from the STACK and place it in the P until left parenthesis is encountered
b) Remove the left parenthesis
[ End of If ]
[ End of Step 2 loop ]
• Complexity – Ø(n), where n be the number of tokens in the expression
Infix to postfix
conversion infixVect
(a+b-c)*d–(e+f)
postfixVect
Infix to postfix conversion
stackVect
infixVect
a+b-c)*d–(e+f)
postfixVect
(
Infix to postfix conversion
stackVect
infixVect
+b-c)*d–(e+f)
postfixVect
a
(
Infix to postfix conversion
stackVect
infixVect
b-c)*d–(e+f)
postfixVect
a
+
(
Infix to postfix conversion
stackVect
infixVect
-c)*d–(e+f)
postfixVect
ab
+
(
Infix to postfix conversion
stackVect
infixVect
c)*d–(e+f)
postfixVect
ab+
-
(
Infix to postfix conversion
stackVect
infixVect
)*d–(e+f)
postfixVect
ab+c
-
(
Infix to postfix conversion
stackVect
infixVect
*d–(e+f)
postfixVect
ab+c-
Infix to postfix conversion
stackVect
infixVect
d–(e+f)
postfixVect
ab+c-
*
Infix to postfix conversion
stackVect
infixVect
–(e+f)
postfixVect
ab+c-d
*
Infix to postfix conversion
stackVect
infixVect
(e+f)
postfixVect
ab+c–d*
-
Infix to postfix conversion
stackVect
infixVect
e+f)
postfixVect
ab+c–d*
(
-
Infix to postfix conversion
stackVect
infixVect
+f)
postfixVect
ab+c–d*e
(
-
Infix to postfix conversion
stackVect
infixVect
f)
postfixVect
+ ab+c–d*e
(
-
Infix to postfix conversion
stackVect
infixVect
)
postfixVect
+ ab+c–d*ef
(
-
Infix to postfix conversion
stackVect
infixVect
postfixVect
ab+c–d*ef+
-
Infix to postfix conversion
stackVect
infixVect
postfixVect
ab+c–d*ef+-
Infix to Postfix Conversion using
Stack:Example
Infix Expression : A *(B + C) /D