Ds Module 1
Ds Module 1
TO DATA
STRUCTURES
BASIC TERMINOLOGY
int arr[10];
Where int specifies the data type or type of elements arrays stores.
“arr” is the name of array & the number specified inside the
square brackets is the number of elements an array can store, this
is also called sized or length of array.
Example:
#include <stdio.h>
#include <stdlib.h>
printf("Enter elements of array: ");
int main()
{ for(i = 0; i < num; ++i)
int num, i, *ptr; {
printf("enter number of printf("Enter element %d: ", i+1);
elements: "); scanf("%d", ptr+ i);
scanf("%d", &num); }
//allocate memory for nor of
elements dynamically printf ("Array elements are:");
ptr = (int*) malloc( num* for(i=0; i< num; i++)
sizeof(int));
printf ("%d ",*(ptr+i));
if(ptr == NULL)
{ free(ptr);
printf("error! memory not }
allocated.");
exit(0);
}
realloc() in C:
realloc () function modifies the allocated memory size by
malloc () and calloc () functions to new size.
If enough space doesn’t exist in memory of current block to
extend, new block is allocated for the full size of reallocation,
then copies the existing data to new block and then frees the
old block.
Syntax:
1. Input: There are zero or more quantities that are externally supplied.
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int key)
{
if (right >= left)
{
int mid = left + (right - left) / 2;
if (arr[mid] == key)
return mid;
if (arr[mid] > key)
return binarySearch(arr, left, mid - 1, key);
else
return binarySearch(arr, mid + 1, right, key);
}
return -1;
}
Algorithm 3:Tower of Hanoi using recursion
Example 1:Tower of Hanoi when only one disk and towers A, B,
and C are given:
Example 2:Tower of Hanoi when Two disk and towers A, B, and C
are given: Move 1 disc from A to B using C
int main()
{
int no_of_disks ;
printf("Enter number of disks: ");
scanf("%d", &no_of_disks);
toH(no_of_disks, A,B,C);
return 0;
}
STRUCTURE AND UNION
Structures:
A structure is a collection of itmes of different data types, where each item is
identified as to its type and name.
Struct Person
{
char name[10];
int age;
float salary;
};
Dot operator(.) is used to access a particular member of the structure.
strcpy(person.name,"james") ;
person.age=35
person.salary = 35000;
We can create our own structure data types by using the typedef statement as below:
typedef struct students
{
char name[50];
char branch[50];
int ID_no;
} stu;
Variables can be declared as follows:
Stu stu1,stu2;
Structures cannot be directly checked for equality or inequality. So, we can
write a function to do this.
We can embed a structure within a structure.
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}DATE;
}emp1={“Rahul”,454,120000,{ 12,2,2000}};
Self-Referential Structures
• A self-referential structure is one in which one or more of
its components is a pointer to itself.
• These require dynamic storage management routines
(malloc & free) to explicitly obtain and release memory.
• They are extensively used to build complex and dynamic
data structures such as linked lists and trees.
Struct Node
{
int data ;
struct node * link ;
};
Consider three structures and values assigned to their respective
fields:
Node item1,item2,tem3;
Item1.data=‘a’;
Item2.data=‘b’;
Item3.data=‘c’;
Item1.link= Item2.link= Item3.link=NULL;
We can attach these structures together as follows:
Item1.link=&item2;
Item2.link=&item3;
c1.m=10;
c1.x= 20
we first place a value in the tag field. This allows us to determine which
field in the union is active. We then place a value in the appropriate field
of the union.
POLYNOMIAL ABSTRACT DATA TYPE
A polynomial is a sum of terms, where each term has a form axe , where
x=variable, a=coefficient and e=exponent.
For ex, A(x)=3x20+2x5+4 and B(x)=x4+10x3+3x2+1
Operations:
Here,
Row→ index of row, where non-zero element is located
Column→ index of column, where non-zero element is
located
Value→value of non zero element is located at index.
TRANSPOSING A MATRIX
• To transpose a matrix ,we must interchange the rows and columns.
• Each element a[i][j] in the original matrix becomes element b[j][i]
in the transpose matrix.
• Algorithm To transpose a matrix:
Example:
THE STRING ABSTRACT DATA TYPE
The string, whose component elements are characters. As an ADT, we
define a string to have the form, S = So, .. . , where Si are characters taken
from the character set of the programming language.
If n = 0, then S is an empty or null string.
There are several useful operations we could specify for strings.
we represent strings as character arrays terminated with the null
character \0.
Copy one string to another string
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
gets(s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
puts(s2);
return 0;
}
Concatenation of two Strings
void main()
{
char str1[25],str2[25];
int i=0,j=0;
printf(" Enter First String:\n");
gets(str1);
printf(" Enter Second String:\n");
gets(str2);
while(str1[i]!='\0’)
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0’; //optional
printf("Concatenated String”);
puts(str1);
}
Program :To compare 2 strings
#include<stdio.h>
main()
{
char str1[5],str2[5];
int i,temp = 0;
printf("Enter the string1 value: ");
gets(str1);
printf(" Enter the String2 value: ");
gets(str2);
for(i=0; str1[i]!='\0’ ||str2[i]!=‘\0’;i++)
{
if(str1[i] == str2[i])
temp = 1;
else
temp = 0;
}
if(temp == 1)
printf("Both strings are same.");
else
printf("Both string not same."); }
String insertion:
Assume that we have two strings, say string 1 and string 2, and that
we want to insert string 2 into string 1 starting at the ith position of
string 1. We begin with the declarations:
Inserting substring into the given string without built in
function
#include <stdio.h>
#include <string.h>
int main()
{
char S1[50], S2[15];
int pos, i, l1, l2;
printf("Enter String :--> ");
gets(S1);
printf("Enter Substring :--> ");
gets(S2);
printf("Enter position from where do wish to insert :--> ");
scanf("%d", &pos);
l1 = strlen(S1);
l2 = strlen(S2)
for(i = pos; i <l1; i++)
S1[pos+l2] = S1[i];
for(i = 0;i < l2; i++)
S1[pos + i] = S2[i];
puts(S1);
}
Pattern Matching:
KMP(Knuth, Morris, Pratt ) Algorithm for Pattern Searching
Operations:
TOP= -1
int peek()
{
return stack[top]; //prints the value to which the 'top' points
}
Write a program in C to implement push, pop and display operations for stacks
using arrays.
void Display()
#include <stdlib.h> {
#define SIZE 4 if (top == -1)
int top = -1, { printf("\nUnderflow!!"); }
int stack[SIZE]; else {
void push()
{ int x;
printf("\nElements present
if (top == SIZE - 1) in the stack: \n");
{ for (int i = top; i >= 0; --i)
printf("\nOverflow!!"); printf("%d\n", stack[i]); }
} }
else
{ int main()
printf("\nEnter the element: "); {
scanf("%d", &x);
top = top + 1;
push(6);
stack[top] = x; Push(8);
}} Push(10);
void pop() Push(12);
{ Display();
if (top == -1) Pop();
{ Pop();
printf("\nUnderflow!!"); Display();
}
else { printf("\nPopped element: %d", stack[top]);
Return 0;
top = top - 1; } } }
STACK APPLICATIONS: POLISH NOTATION
Expressions: It is sequence of operators and operands that reduces to a single value after
evaluation is called an expression.
X=a/b–c+d*e–a*c
In above expression contains operators (+, –, /, *) operands (a, b, c, d, e).
Expression can be represented in in different format such as
•Prefix Expression or Polish notation
•Infix Expression
•Postfix Expression or Reverse Polish notation
Infix Expression: In this expression, the binary operator is placed in-between the operand.
The expression can be parenthesized or un- parenthesized.
Example: A + B
Operators Symbols
Parenthesis ( ), {}, [ ]
Exponents ^
4. If the incoming symbol is ')', pop the stack and print the operators until
the left parenthesis is found.
5. If the incoming symbol has higher precedence than the top of the stack,
push it on the stack.
6. If the incoming symbol has lower precedence than the top of the stack,
pop and print the top of the stack. Then test the incoming operator
against the new top of the stack.
7. If the incoming operator has the same precedence with the top of the
stack then use the associativity rules. If the associativity is from left to
right then pop and print the top of the stack then push the incoming
operator. If the associativity is from right to left then push the incoming
operator.
8. At the end of the expression, pop and print all the operators of the stack.
Consider the following Infix Expression...
(A+B)*(C-D)
The final Postfix Expression is as follows...
AB+CD-*
Example 2: A*(B*C+D*E)+F:
Program to convert infix to postfix expression
#include <limits.h> void push(char oper)
#include <stdio.h> {
#include <stdlib.h> if(isFull())
#define MAX 20 printf("Stack Full!!!!");
char stk[20]; else{
int top = -1; top++;
int isEmpty() stk[top] = oper;
{ }
return top == -1; }
} int checkIfOperand(char ch)
int isFull() {
{ return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
return top == MAX - 1; }
} int precedence(char ch)
char peek() {
{ switch (ch)
return stk[top]; {
} case '+':
char pop() case '-': return 1;
{
if(isEmpty()) case '*':
return -1; case '/': return 2;
char ch = stk[top];
top--; case '^': return 3;
return(ch); }
} return -1;
}
int covertInfixToPostfix(char* expression)
while (!isEmpty())
{
expression[++j] = pop();
int i, j;
for (i = 0, j = -1; expression[i]; ++i)
expression[++j] = '\0';
{
printf( "%s", expression);
if (checkIfOperand(expression[i]))
}
expression[++j] = expression[i];
else if (expression[i] == '(')
int main()
push(expression[i]);
{
else if (expression[i] == ')')
char expression[] = "((x+(y*z))-w)";
{
covertInfixToPostfix(expression);
while (!isEmpty( ) && peek() != '(')
return 0;
expression[++j] = pop();
}
if (!isEmpty( ) && peek( ) != '(')
return -1;
else
pop();
}
else
{
while (!isEmpty() &&
precedence(expression[i]) <= precedence(peek()))
expression[++j] = pop();
push(expression[i]);
}
EVALUATION OF POSTFIX EXPRESSION
The evaluation process of postfix expression is simpler than the evaluation
of infix expressions because there are no parentheses to consider.
To evaluate an expression, make a single left-to-right scan of it.
• Computer the result of op2 / op1, and push it into the stack. Note
the order i.e.i.e. op2 / op1 should not be changed otherwise it will
affect the final result in some cases.
At last, st will consist of a single element i.e. the result after evaluating the
postfix expression.
Example 1:Consider the expression: exp= “2 3 1 * + 9 -“
Scan 2, it’s a number,
There are no more elements to scan, we return the top element from
the stack (which is the only element left in a stack).
So the result becomes -4.
Example 2:Evaluate the postfix expression:456*+
Example 3: Evaluate the postfix expression:5 3+8 2 -*
Program to evaluate postfix expression.
#include <stdio.h> int evaluate(char* expression) {
#include <stdlib.h> int i = 0;
#define MAX_SIZE 100 char symbol = expression[i];
// Stack implementation int operand1, operand2, result;
int stack[MAX_SIZE]; while (symbol != '\0') {
int top = -1; if (symbol >= '0' && symbol <= '9') {
void push(int item) { int num = symbol - '0';
if (top >= MAX_SIZE - 1) { push(num);
printf("Stack Overflow\n"); }
return; else if (is_operator(symbol)) {
} operand2 = pop();
top++; operand1 = pop();
stack[top] = item; switch(symbol) {
} case '+': result = operand1 + operand2; break;
int pop() { case '-': result = operand1 - operand2; break;
if (top < 0) { case '*': result = operand1 * operand2; break;
printf("Stack Underflow\n"); case '/': result = operand1 / operand2; break;
return -1; }
} push(result); }
int item = stack[top]; i++;
top--; symbol = expression[i]; }
return item; } result = pop();
int is_operator(char symbol) { return result; }
if (symbol == '+' || symbol == '-' || int main() {
symbol == '*' || symbol == '/') { char expression[] = “2 3 1 * + 9 –”;
return 1; } int result = evaluate(expression);
printf("Result= %d\n", result); return 0; }