L11 dynamic data structures

Page 1

emeronTI11 ³ Dynamic Data Structures

I. Say about pointer again : pointer Address p.

Ca variable pÞúk Address ¬minEmnpÞúktMéleT¦ dUecñH *p CaTinñn½yEdlpÞúkkñúg b¤niyay müa:geTot p Ca pointer point to variable EdlpÞúk value *p .

II. Dynamic variable:

bNþa variable manRbePTTinñn½y/ EdleyIgFøab;sikSaknøgmkdUcCa Array, int, float ... ehAfa static variable eRBaHvaRtUv)ankMNt;niymn½yCaRsac;muneBl Declaration variable . ry³eBlkekIt static variable KWCary³eBlén karkekItnUvkMNat;kmμviFIEdlpÞúkvaEdr . EtbNþa Variable k¾GacRtUv)ank¾ekItedayrebob dynamic . mann½yfa kekIteLIgenAeBleyIg Run kmμviFI . dUecñH Variable enHminRtUv)ankMNt;niymn½yCamuneT . Variable RbePTenHehAfa Dynamic variable . Dynamic variable KμaneQμaHeT ¬eRBaHkardak;eQμaHkarBit KWkartageGayvanUv Address kMNt;mYy¦ . karbegáIt Dynamic variable niglubvaeTAvij RtUvGnuvtþn_edayEpñkbNþa function dUcCa malloc ( ) nig free ( ) EdlmanRsab;kñúg Library <stdlib.h> . kar Access CamYy 223


RtUvGnuvtþn_edayEp¥kbNþa Variable RbePT pointer (Pointer Variable ) . bNþa pointer Variable RtUvkMNt;Tinñn½y dUcCa Static Variable Edr . ¬mann½yyfa maneQμaH nigRtUv Declaration PøamenAEpñkxagedImkñúgEpñk Declaration Variable nigRtUv)aneRbIedIm,IpkúÞ Address rbs;bNþa Dynamic Variable ) . Ex1: Declaration pointer nigbegáIt Dynamic Variable: Dynamic variable

int *pNumber; pNumber = (int*) malloc (100) ;

/*Declaration pointer variable*/ /*Create Dynamic Variable*/

kMNat;kmμviFIxagelIpþl;eGayeyIg 100 bytes kñúg memory nigtag Address of memory enHeTAeGay pNumber . 100 bytes enHeRbIsMrab;pÞúk %0 cMnYnKt; . ebIcg;)an memory eGayRtwmRtUvsMrab; &% cMnYnKt;/ eyIgsresrdUcxageRkam ³ int *pNumber; pNumber = (int*) malloc (75*sizeof (int));

dUcKñacMeBaHbNþakar Declaration epSg/ eyIgsresr ³ char *cPtr; cPtr = (char *) malloc (l50*sizeof (char)); float *fPtr; fPtr = (float*) malloc (55*sizeof (float));

eyIgnigsikSa]TahrN_sþIGMBiI malloc function dUcxageRkam ³ Ex2: eRbI Function malloc (memory allocaion) # include <stdio.h> # include <conio.h> # include <string.h> # include <alloc.h> # include <process.h> int main (void) { char *str ; /*allocate memry for string*/ if ((str = ( char *) malloc (10) = = NULL) { printf (“\n there isn’t enough memory”) exit (1); } /* copy “Hello” into string */ strcpy (str, “Hello”); /* free memory */ 224


free (str); return 0; }

kñúg]TahrN_xagelI/ eyIg)an

Note: Declaration pointer string str if ((str = (char*) malloc (10) = = NULL) { printf (“\n there isn’t enough memory”); exit (1); }

. bnÞab;mkkMNat;kmμvFi I

nigerobcM dynamic memory sMrab; 10 chapters nigkñúgdMNak;kalenHmankarRtYtBinitüemIl computer man memory RKb;RKan;b¤Gt; ? edayrebobRtYtBinitüemIl lTæpl pointer str mantMélCa NULL b¤Gt; ? eyIgGaceRbI function farmalloc edIm,Ipþl;nUv memory FMCag malloc . Function exit (1) ykecjBI file < process.h> Statement (char *) malloc (10)

eyIgyl;fa erobcMpþl; tMbUgrbs; memory .

RbePT char nig lTæplrbs;vaCa Address enHGnuvtþn_cMeBaHRbePtTinñn½y ³ int, float, long, char,

dynamic memory Function

double .... Syntax: (datatype *) malloc(sizeof(memory))

lTæplrbs; statement enHCanic©Cakal Ca address mYy nigCa Address dMbUgrbs; memory EdlRtUvpþl;/ kñúgenaH data type CaTinñn½y . Syntax: (datatype*)

225


CaRbePT

pointer

(datatype

*)

. ]TahrN_ convert

(float) n

mann½yfa

CaRbePT

pointer

convert n point

eGayeTACacMnYnBit . to datatype .

dUecñHeyIgGacsresrdUcxageRkam ³ pointer malloc(sizeof(memory))

kñúgkarN_cg;begáIt Dynamic memory eGayRbePTTinñn½y minEmnCa int, float, double, eBalKwRbePT TInñn½yEdleyIgCaGñkbegáIt/ eyIgRtUveRbI function calloc ( ) .

long,

Syntax: (datatype*) calloc (n, sizeof (object)); Ex: struct persont { char name[80]; int age; char Address[25]; }; struct person *ptr; /* Declaration pointer person */

sMrab;eGay 10 nak; dUcxageRkam ³ calloc (10, sizeof (struct person));

eRbI

eGay

Ex3: Function calloc string : # include <stdio.h> # include <alloc.h> # include <string.h> int main (void) { char *str = NULL ; /* allocate memory for string */ str = (char *) calloc (10, sizeof (char)); /* copy “Hello” into string */ strcpy (str, “Hello”); /* display string */ printf (“\n String is %s \n”str); 226

ehIyeyIgbegáIt

memory


/* free memory */ free (str); return 0; } Function realloc ( )

Ca function begáIteLIgvijnUv memory : (datatype *) realloc (buf_ptr, newsize);

kñúgenaH buf_ptr Ca pointer kMBug point to memory EdlRtUv)anbegáIt pþl;eGayBIelIkmun . newsize CaTMhMfμI EdlRtUvbegáIt nigpþl; GacFMCag b¤tUcCagmun . Ex4: # include <stdio.h> # include <conio.h> # include <string.h> int main (void) {

char *str ; /* allocate memory for string */ str = (char *) malloc (10); strcpy (str, “Hello”); printf (“ \n string %s \n Address %p \n”, str, str); str = (char*) realloc (str,20); printf (\n string %s \n New Address %p \n”str, str); free (str); return 0;

}

227


III. Heap memory nigrebobbegáIt Dynamic variable :

bNþa dynamic variable EdlbegáIteLIgeday malloc RtUv)an C erobeTAkñúg Block free memory ehAfa HEAP . Pasa C RKb;RKg Heap tamry³ pointer of Heap KW HeapPtr . pointer of Heap Canic©Cakal point to bype free dMbUgrbs; Block free memory rbs; Heap . ral;eBl call malloc ( ), pointer of Heap RtUv)anpøas;TItaMgEpñkxagelIén block free memory bNþa byte mYycMnYnsmmUl nwgTMhMrbs; dynamic variable EdleTIbbegáIt)an . cMeBaHGñksresrkmμviFI/ Heap KWCamUkdæanRKwHEdlRtUvkþab;eGay)an .

Ex5:

rkcMnYn prime

# include <stdio.h> # include <conio.h> main ( ) {long *primes = NULL, *start = NULL, *open = NULL, trial = 0; 228


int i = 0, found = 0; total = 0; printf (“\n How many primes :”); scanf (“%d”, &total); primes = (long*) malloc (total*sizeof (long)); if (primes = = NULL) {printf (“\n there isn’t enough memory !!”); return 0; } /* 3 primes

tMbUgEdleyIgdwg */

*primes = 2; *(primes+1) = 3; *(primes+2) = 5; open = primes + 3; /*

yk Address free bnþrbnÞab;eTot */

trial = 5; do {

yktMé;bnþbnÞab;eTotedIm,IRtYtBinitü */ start = primes; /* start point to EpñkdMbUgrbs;prime */ trial + =2; /*

found = 0; for (i = 0; i < open-primes; i++) if (found = (trial % *start ++) = = 0) break; if (found = = 0) /*

rkeXIjcMnYnfμI */

*open ++ = trial; }

while (open – primes < = total);

for (i = 0; i <5 *(total /5); i+ = 5) /*display 5

elxmþg */

printf (“\n%12ld %12ld %12ld %12ld %12ld”, *(primes + i), * (primes +i + 1), *(primes + i +2), *(primes +i +3), *(primes +i + 4)); printf (“\n”); 229


for (i = total – (total%5); i < total; i++ ) printf (“%12d”, (primes +i )); /*display

EpñkenAsl; */

} The Result is How 2 13 31 53 73

many 3 17 37 59 79

primes: 5 19 41 61 83

25 7 23 43 67 83

11 29 47 71 97

IV. Linked List :

eBleyIgcg;begáIt List mYy/ ]TahrN_ List of Employee, ehIyeyIgdwgcMnYn mnusSBitR)akd enaHeyIgGaceRbI Array of struct edIm,IbegáIt eRBaHvamanlkçN³gayRsYl . EtebIeyIgminsÁal;cMnYnmnusSCamunenaH eyIgKb,IeRbI Dynamic Variable, eRBaHvamanlkμçN³ kñúgkarsnSMsMéc memory ¬eBlNaeyIgRtUvkareTIbeyIgbegáItvamkeRbI¦ . Memory eRbIsMrab; static Variable TaMgGs;kñúg computer IBM_PC KWmanEt 64KB eBalKWmYy Segment . a/ Create a Linked List:

cUrsresrkmμviFIbegáIt Linked List én

employee

Ex: # include <stdio.h> # include <conio.h> # include <alloc.h> struct employee { char name[30]; int age; struct employee *next; }; main ( ) 230

mYy


{

struct employee *last; struct employee *ptr; char name[30]; last = NULL; /* Read form Keyboard to List */ do { printf (“\n name :”); gets (name); if (name[0] != ‘\0’) { ptr = calloc (1, sizeof (struct employee )); /*Read Value of employee */ strcpy (ptrÆname, name); /*ptrÆname = name */ printf (“\n Age :”); scanf (“%d”, &ptrÆage); while (getchar ( ) != ‘\n’); ptrÆnext = last; last = ptr; } } while (name[0] != ‘\0’); /* control and read again to list */ printf (“\n\n List of Employee :”); ptr = last; while (ptr != NULL ) { printf (“Name : %s \n”, ptrÆname); printf (“Age : %d \n\n”, ptrÆage); ptr = ptrÆnext; /* ptr point to next record */ } getch ( ); return 0; }

]bmaeyIg Read bBa©ÚltamlMdab; ³ Mr one, 1 age, Mr two, 2 age... last KwCa pointer Variable, Canic©Cakal point to last of list . eBlcab;epþIm Run program KWeyIgtag last = NULL mann½yfa List Empty . Explain:

231


Ca

name employee

variable

RbePT

string

eRbIsMrab;

Read from keyboard

nUveQμaHrbs;

.

ebI name minEmnCa string TeT/ eyIg test edayrebob ³ name[0] != ‘\0’; edIm,IdwgfamaneQμaHfμIRtUvEfmeTA kñúg List b¤Gt; ? Procedure calloc (--- ); nwgbegáIt Dynamic Variable . dynamic Variable man field mYyeQμaH Next ¬Ca pointer variable) ehIyeyIgcg;eGay field next énFatuEdleTIbbegáIt Canic©Cakal point to FatuEdlbegáIteLIgmunvabnþic . ptrÆnext = last;

ral;eBleyIgeRbI calloc ( ) enaH ptr min point eTA Dynamic Variable EdlbegáItmun²enaHeT/ EteyIg k¾min)at; Address rbs;BYkvaEdr edayEp¥kelI Linked List CakareRsc . Statement last = ptr;

nwgeFVIeGay last point to last record in linked list ehIyEdlCanic©Cakal ptr k¾ point to last record Edr .

KMnUsbMRBYj +

cab;epþIm³ Last

+ Loop

¬Kμan point eTANATaMgGs;¦

NULL

TI 1³

Last Mr One 232

1


ptr

Next

+ Loop

TI2³

NULL

ptr = calloc (1, sizeof (struct employye)); strcpy (ptrÆname, name); printf (“Age :”), scanf (“%d”, &ptrÆage); while (getchar ( ) != ‘\n’);

ptr

point to Mr two

2 next Mr One

1

Last

ptr Æ next = last; last = ptr; ptr Mr two

2

next

last

Mr One

dUcxagelIehAfa LIFO ¬cUlmunecjeRkay/ cUleRkayecjmun¦ . Linked List

Name : MrOne Age : 1 Name: Mr two Age : 2 List of Employee: Name : Mr Two 233

(Last In, First Out)

ehAfa

Stack

1


Age : 2 Name : Mr One Age : 1

eBlenHeyIgcg;EfmFatufμITI3 (Mr Three, Age 3) eTAkNþalFatuBImun³ ¬]bmafaeyIgeRbI last CA pointer point to last of list dUcxagelI ¦ b/ Insert :

struct employee *Q; Q = calloc (1, sizeof (struct employee)); strcpy (QÆname, “Three”); QÆAge = 3; /* find position to insert */ ptr = last; while ((ptr != NULL) && (strcmp (ptrÆname, “Mr Two”))) ptr = ptrÆnext; QÆnext = ptrÆnext; ptrÆnext = Q;

c/ Function Create List : 234


kñúg EpñkxagelI/ eyIg)anbegáIt Linked vaEfmeTotedayeRbI Function create List :

List

dUckñúg]TahrN_/ eyIgcg;

update

Void create_list (struct people ** first);

kñúgenaHeyIgeRbI first CA pointer point to pointer point to FatumYyrbs; list . mann½yfaeyIgEfmFatufμI (New record) mYyeTAkñúg list rbs;eyIgRtg;TItaMgEdl pointer first munenHkMBug point to enaH . Ex7: Function create list : # include <stdio.h> # include <conio.h> # include <stdlib.h> # include <alloc.h> struct person {char name[30]; int age; struct person *next; }; void create_list (struct person **first); main ( ) {struct person *last; create_list (&last); printf (“\n\n List of Employee : \n”); ptr = last; while (ptr!= NULL) {printf (“Name :%s \n”, ptrÆname); printf (“age :%d \n\n”, ptrÆage); ptr = ptrÆnext; /* ptr point to next record */ } getch ( ); 235


return 0; } void create_list (struct person **alast) {

struct person *ptr; char name[30]; *alast = NULL; do {printf (“\n Name :”); gets(name); if (name[0]; != ‘\0’) { ptr = colloc (1, sizeof(struct person)); strcpy (ptrÆname, name); printf (“Age :”); scanf (“%d”, &ptrÆage); while (getchar ( ) != ‘\n’); ptr Æ next = *alast; *alast = ptr; } } while (name[0] != ‘\0’);

}

d/ Delete :

pÞúyBI insert, eBalKWlubmYy Record ecjBI List, . ]TahrN_cg;lub record EdlmaneQμaH Tree ecjBI list eBlenaHeyIgRtUveRbI Q kñúgeBlrk Record EdlmaneQμaH Three . eBlrkeXIjehIyeyIglubvaecj edayrebob BIry:agxusKña . Struct person *Q, *P; /* Search record for delete */ P = last; name = “three”; while ((P != NULL ) && (strcmp (PÆname, name ))) {

Q = P; 236


P = PÆnext ; } /* delete */ if ( P == last ) last = PÆnext; else QÆnext = PÆnext;

e/ Parameter is a pointer dynamic :

GaceRbICa Parameter rbs; subprogram )an/ ]TahrN_ eyIgsresr dUcxageRkam³

dynamic Variable Function Insert

void insert (person * Q); { ... };

eyIgGacsresr Function mYyEdlmanlTæplCa pointer . * person TT (peron *last); { struct person *p1, *p2; p1 = last; last = NULL; do { p2 = p1Ænext; p1Ænext = last; last = p1; p1 = p2; } while (p1 == NULL ); return last; };

+

muneBlehA Q = TT (last); last

point Three

3

Two

2

One

1 NULL

237


+

eRkayBIehA Q = TT (last); Q

last

point Three

3

Two

2

One

1

NULL

f/

RbePTTinñn½y FIFO :

FIFO (First In First Out)

CaRbePT Memory EdlTinñn½yNacUlmun ecjmun cUleRkay

ecjeRkay. Ex8: # include <stdio.h> # include <conio.h> # include <alloc.h> # include <stdlib.h> struct person {char name[30]; int age; struct person *next; } people; main ( ) {

struct person *last, *first, *ptr; char name[30]; first = NULL; do {prinf (“\n Name :”); gets (name); if (strcmp (name, “”))

/* create new record */ 238


{ptr = colloc (1, sizeof (struct person)); strcpy (ptr Æ name, name ); printf (“Age : “); scanf (“%d”, &ptr Æ age); ptr Æ next = NULL; if (first != NULL) last Æ next = ptr; else first = ptr; last = ptr; while (getchar ( ) != ‘\n’); }; } while (name[0] != ‘\0’);

/* Record FIFO again */ ptr = first; while (ptr != NULL) {printf (“%s\n”, ptr Æ name); printf (“%d\n”, ptr Æ age); ptr = ptr Æ next; }; }

=====*===== 239


sMnYr 1.

]bmaman x nig y manRbePTCa pointer dUcKña . sYrfa RbmaNviFIxageRkam ³ x=y;

nig *x = *y ; etIsmmUlnwgKñab¤Gt ; ? ¬cUrBnül ;¦ ? 2. GFib,ayskmμPaBrbs ; FIFO edayKUskMnUsbMRBYjCamYy insert . 3. cUr print Address rbs; Variable NamYymkelI screen . 4. sresrkmμviFIGFib,ayBIkarbegáIt Linked list 5. cUrBinitükmμviFIxageRkammankMhusGVIxøH ? cUrEkkMhus ?

Algorithm delete

nig

struct Myrecord { int Num; Myrecord *next; }; struct Myrecord *Head, * Tail, *T;

]bmaeyIg)anbegáIt linked list 20 node, Edl Head nig Tail point to node dMbUgnig node cugeRkay . eyIgRtUvlub node TaMgGs;kñúgeBlEtmYy */ {

/*

T = Head; while (T != NULL) {Dsiplose (Head); Head = Head Æ Next; T = Head; }; 240


Head = NULL; Tail = NULL; T = NULL; }

=====*=====

241


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.