Sie sind auf Seite 1von 48

Introduction to Data Structures

Algorithm:- A stepwise procedure to solve a problem written in any language.


Program :-A stepwise procedure to solve a problem written in a Programming
Language.
The three stages of solving the problems.
The selection of an appropriate mathematical model(including data structures).
The formulation of algorithms based on the choice made in stage1.
The design of storage structure for the data structures obtained in stage1
Data structure:- The possible ways in which the data items or atoms are legally related
define different data structures.
Group of data items or atoms with some logical relationship on which
some set of operations can be performed is called as a data structure.
Linear Data Structure:- A data structure with adjacency relationship among the data
items or atoms called as a linear data structure.
ex: lists, stacks, queues.
Non-Linear Data Structure:- It is a data structure in which there is no adjacency
relationship among the data items or atoms.
ex: trees ,graphs.

Storage Structure:- The representation of a particular data structure in the memory of a


computer is called a storage structure.
ex: array rep., linked list rep.

Difference between recursive and iterative programs

Recursion:- If a function is calling itself then it is called as recursion


ex: int functional(int n)
{ /* computing factorial of a positive number */
if(n = = 0)
return(1);
else
return(n*factorial(n-1));
}

Iterative::-

ex: int factorial(int n)


{ /* computing factorial of a positive number */
int i ,fact =1;
for( i=1;i< =n;i++)
fact * =i;
return(fact);
}

Introduction to List
List is a linear data structure.
List:- A group of elements referenced with a single name ,consisting of same type with
variable no. of elements is called as a List

List operations:I
Find ,Insert ,Delete ,Update ,Merge ,Split ,Append/Concatinate.
ex: Telephone Directory

Array representation of the list:Normally the list is maintained in some order.


a

0
5

1
9

2
13

size-1
16

24

33

45

Find Operation can be implemented with Linear Search or Binary Search.

Algorithm Analysis
When several algorithms are available,the best algorithm is to be selected.
Hence the algorithm is to be analysed.
Resources Required:- Input/output Devises
Memory
CPU Time
Space Complexity:-Estimation of the extra memory locations required for the algorithm.
Time Complexity:- Estimation of the time required for executing the algorithm.

if there are two positive constants C and n0 such that T(N) C f(N)

When
N no
T(N) =(g(N))
when N no

i f there are two positive constants C and n0 such that T(N) C g(n)

T(N) = (k(N)) if and only if T(N) = O(h(N)) and T(N) = (h(N))


T(N) = o(p(N)) if T(N) = O(P(N)) and T(N) (p(N))
O(k) = O(1)
O(n k) = O(n)
k is a constant constant is not having any significance in the time complexity
analysis.
Rule1 :- If T1(M) = O(f(n)) and T2(n) = O(g(n)) ,then
a. T1(n) + T2(n) = max(O(f(n)),O(g(n))).
b. T1(n) * T2((n) = O(f(n) * g(n)).
Rule2:- If T(n) is a Polynomial of degree k, then T(n).= (n k )

Rule3:- If logk n = O(n) for any constant k.This tells us that logarithms grow very
slowly.

Typical growth rates:-

Function

Name

Constant

Logn

Logarithmic

Log2n

Log-squared

Linear

nlogn

n2

Quadratic

n3

Cubic

2n

Exponential

ex:- Running time Calculations

General rules: The running time of a for loop is at most the running time of the statements inside
the for loop(including tests) times the no of iterations.
The total running time of a statement inside a group of nested loops is the running
time of the statement multiplied by the product of the sizes of all the for loops.
The running time of an if /else statement is never more than the running time of
the test plus the larger of the running times of s1 and s2.

Euclids Algorithm for computing GCD is if M > N, then M mod N < M/2.

Searching- Linear/Sequential Search


Its time complexity is O(n) and can be applied on sorted/unsorted lists.
Given an integer x and integers ao,a1 an-1 are already in memory ,find i such that
ai = x , or return i = -1 if x is not in the input.
Assumption:- n is global
int find _linear( int a[ ] ,int x)
{
int i;
/* linear search algorithm */
for(i=0 ;i<n;i++)
{
if(x = = a[i])
return(i);
else
continue;
}
return(-1);
}

Time Complexity:Best Case:- Element may exist in the first place T(n) = O(1) i.e for loop is executing
only once.
Worst Case:- When the element is not existing the for loop/Basic operation is
executed n times
T(n) = O(n).

Average time complexity:T(n) = O(1) + O(n)


2
= O((n+1)/2)
= O(n)

Searching- Binary Search


Its time complexity is O(log2n) and can be applied only on sorted lists.
Given an integer x and integer ao, a1,..an-1 ,which are represented and already in
memory,find i such that ai = x, or return i = -1 if x is not in the input i.e n is global.
int bsearch(int a[] ,int x)
{ /*binary search */
int lb, m, rb;
lb =0;
rb = n-1;
while(lb <= rb)
{
m = (lb+ rb) /2;
if(a[m]<x)
lb = m+1;
else
if(a[m] > x)
rb = m-1;
else
return(m);
}
return(-1);
}

List Find, Insert ,Delete operations


List Insert operation:- (array rep) .Its time complexity is O(n).
Given an integer x and integers ao,a1.an-1, which are presorted in memory ,insert
x in the list and update the no. of elements i.e n is global.

0 1
2 5

2
n-1
16
22
34
39
43
P

Find the position of x:int findpos(int a[] ,int x)


{
/* finding the position of the given element */
int i;
for( i =0 ; i< n; i++)
{
if( x < = a[i])
return(i);
else
continue;
}
return(i );
}
Insert:void insert(int a[],int x)
{ /* inserting an element into an ordered list */
int i,pos;
pos = findpos(a,x);
for(i = n-1 ; i>=pos;i--)
a[i+1] = a[i];
a[pos] = x;
n++;
}

s-1
x=19

Delete Operation (array rep);- Its time complexity is O(n).


Delete the given element x from the list of integers.
void delete(int a[],int x)
{ /* deleting an element from the list */
int pos ,i;
pos = find (a,x);
if(pos = = -1)
printf(%d is not existing,x);
else
{
for(i =pos ;i< n-1; i++)
a[i] = a[n-1];
n--;
}
}
List Merge Operation:-Combining two or more sorted lists into a single sorted
list(without using sorting technique).
Assumption:- n,m,l are global variables
a0
2

1
8

2 n-1
13 16 21 30 35

b0
5

1
11

2
15

3
18

4m-1
20 40 45

2
8

3
11

4 m+n -1

. ..

c 0 1
2
5

s-1
..
s-1

void smerge(int a[] ,int b[] ,int c[])


{ /* simple merging */
int i,j,k;
i = j = k =0;
while((i<n) &&(j<m))
{
if(a[i] <b[j])
c[k++] = a[i++];
else
c[k++]=b[j++];
}
while(i<=n)
c[k++] = a[i++];
while(j<=m)
c[k++] = b[j++];
l = m+n;
}
The time complexity of simple merging is O(m+n)

Reading a list
void readlist(int a[],int n)
{ /* reading a list */
int i ;
for(i = 0 ;i< n; i++)
{
printf(Enter the element:%d ,i++);
scanf(%d,&a[i]);
}
}

Printing a list
void printlist(int a[],int n)
{ /* displaying a list */
int i;
for(i=0 ;i< n;i++)
printf(%4d,a[i]);
}

Interactive menu driven program to implement all the list operations . * a is the
mainlist.

# include<stdio.h>
#define s 100
int n,m,l;
main()
{ /* program to implement all the list operations */
int a[s],b[s],c[s],p,x,y,choice;char c;
/* Farward declarations of all functions */
printf(Enter the no of elements of mainlist);
scanf(%d,&n);
readlist(a,n);
while(1)
{
printf(Enter your choice:\n);
printf(1.For find, 2.For Insert, 3.For Delete \n);
printf(4.For Update, 5.For Merge,6.For Split \n);
printf(7.For Append, 8.For Display, 9.For Quit \n);
scanf(%d, &Choice);
switch(choice)
{
case 1:printf(Enter the value to be searched \n);
scanf(%d,&x);
p = find(a,x);
if(p= = -1)
printf(%d is not existing \n,x);
else
printf(%d is existing in position: %d\n, x,p);
break;
case 2:printf(Enter the element to be inserted\n);
scanf(%d,&x);
insert(a ,x);
break;
case 3:printf(Enter the element to be deleted\n);
scanf(%d,&x);
delete(a,x);
break;
case 4:printf(Enter the elements x,y:\n);
scanf(%d %d, &x ,&y);

update(a,x,y);
break;
case 5:printf(Enter the no of elements of second list\n);
scanf(%d,&m);
readlist(b,m);
smerge(a,b,c);
break;
case 6:printf(Enter the element x \n);
scanf(%d, &x);
split(a,b,c);
break;
case7: printf(Enter the no of elements of second list\n);
scanf(%d,&m);
readlist(b,m);
append(a,b,c);
break;
case8: printf(Enter the list to be displayed:a,b,c);
scanf(%c,&c);
switch(c)
{
case a :printlist(a,n);break;
case b :printlist(b,m);break;
case c :printlist(c,l); break;
}
break;
case 9: exit(0);
default: Printf(Enter your code correctly\n);
}
}
}

Sorting
Arranging the elements in some order(ascending/descending) is known as Sorting.

Classification based the place of the elements.


Internal Sorting:- If all the elements which are to be sorted are in the main memory,the
entire sorting can be done in main memory which is called as Internal Sorting.
ex: selection ,bubble ,insertion ,shell, merge ,quick ,radix & heap sort etc.
External Sorting:-Sorting that can be performed on the elements stored in disks or
tapes are known as external sorting.
ex: Multiway merge sort, Polyphase merge sort .

Classification based the methods


Comparison-based Sorting:- The list is sorted by comparing the elements.
Ex: selection,insertion,merge,etc
Non-Comparison based Sorting:- Without comparing any element with any other
element of the list, the list will be sorted.
ex: Radix Sort.

Selection Sort
Time Complexity
Best Case: O(n2)
Worst Case:O(n2)
Average Case:O(n2)
Space Complexity: 1(inplace)

void selection(int a[] ,int n)


{ /* selection sort algorithm */
int i,j,mindex,temp;
for(i = 0; i<n-1; i++)
{
mindex = i;
for(j = i+1;j<n; j++)
{
if(a[mindex] > a[j])
mindex = j;
}
if(i ! = mindex)
{
temp = a[i];
a[i] = a[mindex];
a[mindex] = temp;
}
}

}
Time complexity:
T(n) = n-1+n-2+. + 3+2+1
= n(n-1)

= n2- n

= O(n) for all the three cases

Bubble Sort
Time Complexity:Tbc(n) = O(n) ,Twc(n) = O(n2), Tavg(n) = O(n2)
Space Complexity:Space Complexity: 1(inplace)
void bubblesort(int a[], int n)
{

/* bubble sort algorithm */


int i, j ,temp,last,exchs =0;
last = n;
for( i=0 ; i< n; i++)
{
last --;
for( j=0 ;j< last; j++)
{
if( a[j] > a[j+1)
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp ;
exchs++;
}
}
if(exchs = = 0)
break;
}

}
Best Case:- only inner for loop is executed n times
T(n) = O(n)
Worst Case:- T(n) = n-1+n-2 +......... +3+ 2+1
= n(n-1)

= n2-n

= O(n2 )

Insertion Sort
Time complexity: Tbc = O(n), Twc(n) = O(n2), Tavg = O(n2)
Space Complexity : one extra location.
It consists of n-1 passes For pass p =1 through n-1,insertion sort ensures that the elements
in position O through p are in sorted order.Insertion sort makes use of the fact that
elements in position O through p-1 are already known to be in sorted order.

a 0
20

1
80

2
11

n-1
37

void insertionsort(int a[], int n)


{ /* insertion sort algorithm */
int j ,p,temp;
for(p =1; p< n; p++)
{
temp = a[p];
for(j= p; j>0 && a[j-1] > temp; j--)
a[j] = a[j-1];
a[j] =temp;
}
}
Time Complexity T(n)=
n
i = 2 + 3+ 4+ ..+ n = (n2)
i=2

95

15

44

A lower bound for Simple Sorting Algorithms:An inversion in an array of numbers is any ordered pair(a(i),a(j)) having the property
that i< j but a[i] > a[j].
The average no of inversions in an array of n distinct numbers is n(n-1)/4
Any algorithm that sorts by exchanging adjacent elements requires (n2) time on average

Shell Sort
Shell sort :- (Donald Shell). One of the first algorithms to break the quadratic time
barrier.
It works by comparing elements that are distant.
The distance between comparisons decreases as the algorithms runs until the last phase,
in which adjacent elements are compared.
Sometimes it is referred to as diminishing increment sort.
Shellsort uses a sequence,h1,h2..ht called the increment sequence.After a phase,using
some increment hk , for every i , we have A[i] A[ i + hk] .All the elements spaced hk
apart are sorted .The file is then said to be hk sorted.
Shells increment sequence:- ht = n/2 hk =[hk+1/2 ]. TWC(n) =(n2)
Hibbards increment sequence:- 1, 3, 7, 2k - 1 TWC(n) =(n3/2), Tavg(n) =(n3/2),
Sedgewicks increment sequence:- 1,5, 19, 41, 109 TWC(n) =O(n 4/3)
9.4i 9.2i + 1 or 4i 3.2i + 1 Tavg(n) =O(n 7/6)

void Shellsort( int a[] , int n)


{ /* Shell sort algorithm */
int i,j, inc ,temp;
for( inc = n/2 ; inc > 0; inc/= 2)
for(i =inc ; i<n ;i++)
{
temp = a[i];
for(j = i; j > = inc; j- = inc)
if(temp < a[j-inc])
a[j] = a[j-inc];
else
break;
a[j] = temp;
}
}
Time Complexity:worst case:- If in the even positions larger elements are stored, in the odd positions
smaller elements are stored and n= 2k then maximum time is required.
hk insertion sorts of n/hk elements i.e T(n) = O(hk (n/hk)2) = O(n2)

Merge Sort
Space Complexity is n and Time Complexity is O(n log2 n).
The fundamental operation in this algorithm is merging two sorted lists.
If n =1, there is only one element to sort and the list is sorted.Otherwise, recursively sort
the first half and the second half.
It gives two sorted halves, which can then be merged together using the merging
algorithm.
This algorithm is a classic divide-and-conquer strategy.
The problem is divided into smaller problems and solved recursively.
The conquering phase consisting of patching together the answers.

void mergesort (int a[ ] , int n)


{
int *ta;
ta = (int *) malloc ( n * sizeof(int));
if( ta = = Null)
printf(Out of Space);
else
{
msort(a, ta, 0, n-1);
free(ta);
}
}
void msort(int a[],int ta[],int lb, int rb)
{ /* merge sort algorithm */
int mid;
if( lb < rb)
{
mid = (lb + rb)/2;
msort(a,ta,lb,mid);
msort(a,ta,mid+1,rb);
merge(a,ta,lb,mid+1,rb);
}
}
void merge(int a[],int tarray,int lpos,int rpos,int rend)
{ /* simple/ two-way merge algorithm */
int i, lend,noe,tpos ;
lend = rpos-1;
tops = lpos;
noe = rend-lpos+1;
while((lpos < = lend) && (rpos < = rend))
if(a[lpos] < = a[rpos]
tarray[tpos++] = a[lpos++]
else
tarray[tpos++] = a[rpos++];
for(i=1; i<= noe; i++)
{
a[rend] = tarray[rend];
rend--;
}
}

Time Complexity:T(1) = 1;
T(n) = 2T(n/2)+n;
T(n/2)
n/2
:
:

= T(n/4) +1
n/4
:
:

T(n/4) = T(n/8)+ 1
n/4
n/8
T(2)/2 = T(1)/1+1
T(n)/n = 1+log2n
T(n) = O(nlog2n)

Quicksort
Space Complexity:- 1
T(n)wc = O(n2)
Tavg(n) = Twc(n) = O(nlog2n)
It is the fastest known algorithm in practice.
Quicksort is a divide-conquer recursive algorithm.
The basic algorithm to sort an array a consists of the following four easy steps:

1.If the number of elements in a is 0 or 1, then return.

2.Pick any element v in a. This is called the pivot.

3.Partition a- {v}(the remaining elements in s) into two disjoint groups . a1 = {X a{ v}| x v } and a2 = { x a {v} | x v }

Return { quicksort(a1) followed by v followed by quicksort(a2)}

Picking the pivot:- First /last element


Random number generation
Median of the three Partitioning
void quicksort( int a[] ,int n)
{
qsort(a, 0, n-1);
}
void qsort(int a[ ] ,int lb, int rb)
{ /* quick sort algorithm */
int i,j ,temp ;
i =lb, j = rb+1;
if(lb < rb)
{
while(1)
{
i++;
while(a[lb] > a[i])
i++;
j--;
while(a[lb]< a [j])
j--;
if(i<j)
{
temp = a[i] ;
a[i] = a[j];
a[j] =temp;
}
else
break;

}
temp = a[lb];
a[lb] = a[j];
a[j] = temp;
qsort(a, lb, j-1);
qsort(a, j+1, rb);
}
}
Time Complexity :- T(n) = T(i) + T(N-i-1) + cn
i is the no of elements in list a1.
Worst Case :- i =0
T(n) = T(0) + T(n-1) +cn
= T(n-1) +cn
T(n-1) = T(n-2) + c(n-1)
T(n-2) = T(n-3) + c(n-2)
;. :
T(3) = T(2) + c. 3
T(2) = T(1) + c.2
n
T(n) = T(1) + c. i = O(n2)
i =2
Best Case:- i =n/2
T(n) = 2T(n/2)+cn
T(n) = T(n/2) + c
n
n/2
Similar to that of merge sort
T(n) = O(nlog 2 n)
n-1
1/ n

T(j)
j=0

is the average time for one list.

Average Case:n-1
T(n)= 2/n

T(j) +c .n
j=0
n-1
T(j) +c .n2

n.T(n) = 2

------I

j=0
n-2
(n-1) T(n-1) = 2 T(j) +c .n-1 2 ----II
j=0
I-II

: n.T(n) = (n+!) T(n-1) + 2.cn

T(n-1)

= T(n-2) + 2c

n+1

n-1

n +1

T(n-1)

= T(n-2) + 2c

n-1

= T(n-3) + 2c

T(n-2)
n

n-1

n-1

.....
T(2)

= T( 1) +

n-2

2c
3
n+1

T(n)

T(1) + 2c i/1

n+1

T(n) =
n+1

O(log2n)

T(n) = O(n log2n)

i=3
n+1
[ . . = loge(n+1) + r- 3 ]
2

Radix Sort
SpaceComplexity : 10n

Time complexity T(n) = O(m x n)

Non Comparision based sorting method


General algorithm:
1.Repeat thru step 6 for each digit in the key.
2.Intialize the pockets.
3.Repeat thru step5 untill the end of the list
4.Obtain the next digit of the key.
5.Insert the record in the appropriate pocket.
6.Combine the pockets to form a new linked list
Example: 42,23 74,11, 65, 57, 94, 30, 73, 84, 61, 81
1st Pass: Distribute
81
61
30
11
----Pocket: 0
1

84
94
74
--4

73
23
--3

42
--2

65
--5

57
--- --6 7

--- --8
9

Combine the pockets


30,11 61,81, 42, 23,73,74,94, 84,65, 57.
IInd Pass: Distribute
11
--- --Pocket: 0 1

23
--2

30
--3

65
42 57 61
--- --- --4
5
6

74
73
--7

84
81 94
--- --8
9

Combine the pockets:


11, 23, 30,42, 57, 61, 65, 73, 74, 81, 84, 94 is the Final Sorted list.

11,23,30, 42, 57, 61, 65, 73, 74, 81, 84, 94 is the Final Sorted List.
To reduce the Space Complexity Radix Sort can be implemented using Linked List.
Each pocket is a Queue.
N is the no of records, M is the no of digits.
Radix Sort(First, n]
1.[Perform Sort]
Repeat through step4 for J = 1, 2,,..M.
2.[Initialize the pass]
Repeat for i = 0, 1, 2,..9.
T[I] = B[I] = Null.
3.[Distribute each record in the appropriate pocket.
Repeat while R NULL.
bj (Obtain Jth digit of the key R
data)
D
Link.If T[D] = Null
Next = R
Then T[D] =B[d] = R
Else T[D] = Link = R
T[D] = R
Link = Null
R
R = Next
4 [ Combine Pockets]
P =0
Repeat while B[P] = NULL
P = P+1
First = B[P]
Repeat for I = P+1, P+2,..9
Prev = T[I-1]
If T[i] Null
Link = B[I]
Then Prev
Else T[i] =PREV
5.[Finished]
Return.

STACK(LIFO) : Array Implementation


Stack is a linear data structure on which the insert and delete operations can be performed
at the same end.(OR) stack is a linear data structure into which the elements are inserted
and deleted in such a way that the last element inserted is to be deleted first.
The most and least accessible elements in a stack are known as the top and bottom of
the stack, respectively.
Stack operations:
* Push(s,x) Inserting an element into the stack.
* Pop(s)- deleting an element from the stack.
* Peep(s,i)-returning the ith element from the top of the stack.
* Change(s,i,x)-updating the ith element from the top of the stack.
Stack Applications:
1.To implement the function calls/Recursion
2. To convert the given infix expression into postfix exp
3. To evaluate the postfix expressions.
4. To check whether the symbols are balanced or not.
5. DFS
Stack ADT:
Stack
(s)

Push(s,x)

y=pop(s)

3 .

-1

n-1
-

tos

insert
delete

or

n-1 n

insert
tos
delete
Push(s,tos,n,x)
1. [check for overflow]
if(tos > n-1)
then printf(Overflow on push)
return
2. [Increment top of the stack]
tos = tos + 1
3. [Insert the element]
s[tos] = x
4. [Finished]
return

Pop(s,tos,)
1. [check for underflow]
if(tos <= -1)
then printf(underflow on pop)
return
2. [Decrement top of the stack]
tos = tos - 1
3. [Return the previous top of the stack]
return (s[tos+1])
Peep(s,tos,i)
1. [Check for underflow]
if(tos i+1 <= -1)
then printf (Underflow on peep)
return(-1)
2. [Return the ith element from tos]
return(s[tos-i+1])

Change(s,tos,i, x)
1. [Check for underflow]
if(tos i+1 <= -1)
then printf (Underflow on peep)
return(-1)
2. [update the ith element with x]
s[tos-i+1] = x
3. [Finished]
return

C functions for stack operations


Assume n(size), tos are global variables.
void push(int s[],int x)
{ /* inserting an element into the stack */
if(tos>= n-1)
printf(Overflow on push);
else
s[++tos] = x;
}
int pop(int s[])
{ /* deleting an element from the stack */
int y;
if(tos < = 1)
{
printf( Underflow on pop);
return(-1);
}
else
{
y = s[tos];
tos--;
return(y);
}
}
Disadvantage:The size n,and top of the stack,tos are taken as global variables.
.

Structure Implementation:stack without global variables:

size
tos
sarray

struct stack
{
int size;
int tos;
int *sarray;
};
struct stack * createstack(int n)
{
struct stack * s;
s = (struct stack *)malloc (sizeof(struct stack));
if(s ==Null)
printf(out of space);
else
{
s->sarray =(int*)malloc (n *sizeof(int));
if( s->sarray = = NULL)
{
printf(out of space);
return(NULL);
}
else
{
s ->size = n-1;
s -> tos =-1;
}
}
return(s);
}

n-1

void push(struct stack *s ,int x)


{
if(s->tos >= s->size)
printf(overflow on push);
else
{
s->tos++;
s->sarray[s->tos] = x;
}
}
int pop(struct stack * S)
{
int y;
if(s-> tos <= 1)
{
printf(underflow on pop);
return(-1);
}
else
{
y = s->array[s->tos];
s->tos--;
return(y);
}
}
Stack Applications
1.For Implementing recursive functions.
ex :- function calls
2. To convert infix expression into postfix form.
General Algorithm:
1.Initialize stack contents to the special symbol #
2.Scan the leftmost symbol in the given infix expression and denote it as the current input
symbol.
3.Repeat through step6 while the current input symbol is not #
4.Remove and output all stack symbols whose precendence values are greater than or
equal to the precedence of the current input symbol.
5.Push the current symbol onto the stack.
6.scan the leftmost in the infix expression and let it be the current input symbol.
+,- (1),

*, / % (2),

a,b,c..(3), #

(0).

i
ie[]

j
a

Pe[ ]

C -functions
int isoperator(char x)
{
if((x= =+)||(x= = -)||(x = = *)||(x = = /))
return(1);
else
return(0);
}
int precendence(Char x)
{
If((x= = *)||( x = = /))
return(2);
else
return(1);
}
top of the stack tos is global.

void intopost(char ine[],char pe[])


{ /* converts given infix expression into postfix expression */
int i, j, k, px,py;
char x, y, s[10]; / * s-> stack array */
tos =-1;
i =j =0;
while(ine[i]! = #)
{
x = ine[i] ;
k = isoperator(x);
if(!k)
pe[j++] =x;
else
{
if(tos!= -1)
{
px =precendence(x);
y =top(s);
py = precendence(y);
while((tos!=-1)&&(px<py))
{
pe[j++] =pop(s);
y = top(s);
py =precendence(y);
}
}
push(s,x);
}
i++;
}
while(tos!=-1)
{
pe[i++] =pop(s);
}
pe[j] = #;
}

Stack Applications
To evaluate the given postfix expression
float Evalpost(Char pe[])
{ /* finds the value of the given postfix expression */
float x,y,z,s[15];
int i =0.
tos = -1;
while( pe[i] ! = #)
{
if(isoperator(pe[i])
{
y=pop(s);
x= pop(s);
switch(pe[i])
{
case + : z = x+y; break;
case - : z = x-y; break;
case * : z = x* y:break;
case / : z = x/y; break;
}
push(s,z);
}
else
{
printf(Enter the value of %c,pe[i]);
scanf(%f,&x);
push(s,x);
}
i++;
}
return(pop(s));
}
*function to check whether given character is symbol or not.
int issymbol(Char x)
{
if((x==()||(x= = ))||(x= = [)||(x= = ])||( x = = { )||( x= = }))
return(1);
else
return(0);
}

*function to check whether the two symbols are counter parts or not(x is a closing
symbol)
int iscounter(Char x,Char y)
{
switch(x)
{
Case ) : if(y= = ()
return(1);
else break;
Case ] : if (y = =[ )
return(1);
else break;
Case } : if( y = = { )
return(1);
else break;
}
return(0);
}
Implementing Two stacks in a single array

Stack1 is grown by incrementing tos and stack2 is grown by decrementing tos.


void push1(int s[] ,int x)
{
if(tos2 tos1= = 1)
printf(stack is full :Overflowerror);
else
s [++tos1] = x;
}

void push2(int s[],int x)


{
if( tos2-tos1 = = 1)
printf(stack is full: Overflowerror);
else
s[--tos2] = x;
}
int pop1[int s[])
{
if(tos1<=-1)
{
printf(underflow on pop1);
return(-1);
}
else
{
tos--;
return(s[tos1++]);
}
}
int pop2(int s[])
{
if(tos2>=n)
{
printf(underlow on pop2);
return(-1);
}
else
{
tos2++;
return(s[tos2-1]);
}
}

Implement n stacks in a single array of m location

tos

-1

14

lb

10

15

14

19

rb

Initialization:
for(i=0 ;i<n ; i++)
{
tos[i] = m/n * i 1;
lb[i] = tos[i] +1;
rb[i] = (i+1) * m/n 1;
void push(int s[],int i,int x)
{
if(tos[i] >= rb[i] )
printf(Overflow on push);
else
{
tos[i]++;
s[tos[i] ] = x;
}
}

int pop (int s[] ,int i)


{
if(tos [i] < lb[i])
{
printf( underflow on pop);
return(-1);
}
else
{
tos[i] --;
return(s[tos[i]+1);
}

QUEUE(FIFO)-Linear Data Structure


Queue is a subclass of lists permits deletions to be performed at one end of a list and
insertions at the other.
The information in queue is processed in the same order as it was received that is on a
first-in ,first-out(FIFO) or a first come,first served(FCFS) basis.

insert(q,x)

y=delete(q)
Queue(q)

y=delete(q)
y=dequeue(q)

exqueue(q,x)

Queue Applications:Queue is a checkout line at a Super market cash register.The first person inline is the first
to be Checked out.
Queue can be found in a time sharing computer system where many users share the
system simultaneously.
In multiprogram concept the os has to maintain different processes in ready queue ,
Waiting queue.etc.
In simulation:Simulation is the process of forming an abstract model from a real situation inorder to
understand the impact of modifications and the effect of introducing various strategies on
the situation.
Simulation allows the user to experiment with real and proposed situations otherwise
impossible or impractical.
The major advantage of simulation is that it permits experimentation without modifying
the real situation.
Military operations,pilot training programme etc.
* Queing theory.

Different types of queues:1.Simple(Linear) queue


2.Circular queue.
3.Deque (double-ended queue).
Simple queue with arrays:Representation of queue

Deletion

Insert
front

rear

Algorithms:qinsert(q,front,rear,n,x)
1. [check for overflow]
if (rear >= n-1)
printf (overflow)
return
2. [Increment rear pointer]
rear++
3. [Insert the element]
q[rear] = x
4. [Is front pointer properly set ?]
if(front = = -1)
front = 0
return
qdelete(q,front,rear)
1. [check for underflow]
if(front = = -1)
printf(underflow)
return(-1)
2. [Delete the element]
y= q[front]
3. [queue empty?]
if(front == rear)
front = rear = -1
else
front = front +1
4. [return the element]
return(y)

C functions for qinsert and qdelete operations


Assuming that n ,front and rear are global varibles
void qinsert(int q[],int x)
{ /* inserts an element into the queue */
if(rear >= n-1)
printf( overflow on insert);
else
{
q[++rear] = x;
if(front = = -1)
front ++;
}
}
int qdelete(int q[])
{ /* deletes front element from the queue */
int y;
if( front = = -1)
{
printf( overflow on delete);
return(-1);
}
else
{
y = q[front];
if( front = = rear )
front = rear = -1;
else
front++;
return(y);
}
}

Disadvantage:The above implementation can be very wasteful of storage if the front pointer F never
manages to catch up to the rear pointer.An arbitrary large amount of memory would be
required to accommodate the elements.
0
1
2.n-1
ex:
x x
front rear
In the above example if we try to insert an element the insert will display an overflow
error even though there are n-2 free locations.

Circular queue
A more suitable method of representing a queue,which prevents an excessive use of
memory , is to arrange the elements q[0],q[1]..q[n] in a circular fashion with q[0]
follows.

Algorithms:
Cqinsert(cq,n,front ,rear, x)
1 [update rear pointer]
if(rear = = n+1)
rear = 0
else rear = rear + 1
2. [overflow ?]
if(front = = rear]
printf(overflow)
return
3. [Insert the element]
cq[rear] = x
4.[Is front pointer properly set ? ]
if(front = = -1)
front = 0;
return

Cqdelete(cq,n,front,rear)
1. [underflow?]
if(front = = -1)
printf(underflow)
return(-1);
2. [Delete the element]
y = cq[front]
3. [Is queue empty?]
if(front = = rear)
front = rear = -1
return(y);
4. [Update front pointer]
if(front = = n-1)
front = 0;
else
front++;
return(y)

Circular queue implementation in c


n,front ,rear Global
void cqinsert(int cq[],int x)
{ /*inserts an element into the circular queue */
int p;
p = rear;
if(rear = = n-1)
rear = 0;
else rear ++;
if(front = = rear)
{
printf( overflow on insert);
rear = p;
}
else
{
cq[rear] = x;
if(front = = -1)
front + +;
}
}
int cqdelete(int cq[])
{ /* deletes front element from the circular queue */
int y;
if(front = = -1)
{
printf(underflow on delete);
return(-1);
}
else
{
y = cq[front];
if(front = = rear)
front = rear = -1;
else
if(front = n-1)
front = 0;
else
front++;
}
return(y);
}

Structure Implementation
Q
qsize
front
rear
qarray

struct queue{
int qsize;
int front;
int rear;
int *qarray;
};
struct queue * Create stack(int n)
{
struct queue * Q;
Q = (structqueue *) malloc (sizeof(struct queue));
if( Q = = NULL)
{
printf( out of space);
return(NULL);
}
else
{
Q -> qsize = n-1;
Q ->front = Q-> rear = -1;
}
return(Q);
}
HOME WORK: WRITE INSERT AND DELETE FUNCTIONS

n-1

Deque(Double ended Queue)


Deque is a linear list in which insertions and deletions are made to or from either end of
the structure.
It is more general than a stack or a queue .
Input_restricted deque allows insertions at only one end.
Out-put-restricted deque permits deletions from only one end.
deletion

insertion
x

insertion
empty deque: dq [ ]

Operations:
leftinsert,
rightinsert,
leftdelete,
rightdelete

x
deletion

leftinsert(dq,n,IL,IR,DL,DR,x)
1. [check for overflow]
if(IL-IR = = 1)
printf(overflow)
return
2. [Decrement IL]
IL =IL-1
3. [Insert the element
dq[IL] = x
4. [check DR for proper value]
if(DR = = n)
DR = DR 1
5. [Finished]
return
* rightdelete-rightmost element is to be deleted
rightdelete(dq,IL,IR,DL,DR)
1. [check for underflow]
if((DL = = -1) &&(DR = = n))
{
printf(underflow)
return(-1)
}
2. [Delete the rightmost element]
if(DR ! = n)
{
y= dq[DR]
if(DR = = IL)
DR = IL = n
else
DR = DR 1
}
else
{
y = dq[IR]
if(IR = = DL)
IR = DL = -1
else
IR = IR 1
}
3. [Finished]
return(y)

Das könnte Ihnen auch gefallen