dynamic data structures - indraprastha institute of ... pointers ? dynamic memory allocation:...

112
Data Structures Rajiv Raman Mukesh Kumar | Monica Sahni | Menika Anand | Rajesh Sethi | Anju Gupta csamazingresources.blogspot.in (Developed as a part of IIITD Workshop for CS Teachers on 16-Aug-2015) Dynamic

Upload: trinhliem

Post on 26-Mar-2018

220 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Data Structures

Rajiv RamanMukesh Kumar | Monica Sahni | Menika Anand | Rajesh Sethi | Anju Gupta

csamazingresources.blogspot.in(Developed as a part of IIITD Workshop for CS Teachers on 16-Aug-2015)

Dynamic

Page 2: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Memory Model● Data stored on ARRAY on consecutive locations.● Example:

1000

Assuming, each element occupy 1 byte each

Assuming, each element occupy 2 bytes each

1001 1002 1003 1004 1005 1006 1007

1000 1001 1002 1003 1004 1005 1006 1007

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7]

A[0] A[1] A[2] A[3]

2

Page 3: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Variables

● Static : Lifetime - life of a program.● Automatic : Lifetime - life of a block._____________________________________● Heap : Lifetime - Between allocation

by new/malloc and freed by using delete/free.

3

Page 4: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Variablesstatic int i=1;//staticint x; //automaticint* p=(int*)malloc(sizeof(int)); //heapint* q = new int;//heapfree(p); delete(q);

4

Page 5: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Memory Segments for Variables

Static Automatic Heap

5

Heap is the segment where dynamic memory allocation

takes place

Page 6: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointers

6

Page 7: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is a Pointer ?● A pointer of type T stores the memory location of

a data of type T.● Examples:

//P points to memory location to hold an int.

int* P; //C points to memory location to hold a char

char* C;7

Page 8: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointer Declarationint Value = 42;int *P = &Value;

P is of type pointer to integer. It stores the location in memory where an integer is stored.

8

01010011101 42 01010011101

PValue

Page 9: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Operators& ( address of)

○ Returns a pointer to an object.○ Address of an object.○ Ex: int A,*P;

P = &A; //P stores the address of A.

* (de-reference)○ Returns value stored at a memory location.○ Ex: int B = *P;

//B stores the value at location P. 9

Page 10: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

& and *int x; //integer xint *p; //p - a pointer to an integerint **q;//q - pointer to a pointer to an int

p = &x; //p points to x.q = &p; //q points to p.

10

Page 11: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dereferenceint y; int* x = &y;We can use *x wherever y occurs.

For example:int y;int* x = &y;*x = 10; // y = 10

11

Page 12: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Quiz

12

Page 13: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?int y = 100;int *x = &y;*x = *x + 1; ++*x; (*x)++; *x++;Values of *x, y after each step.

13

Page 14: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?int y = 100;int *x = &y; // *x = 100, y = 100*x = *x + 1; // *x = 101, y = 101++*x; // *x = 102, y = 102 (*x)++; // *x = 103, y = 103*x++; // *x = arb. y = 103

14

Page 15: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output ?int A = 5, B = 15;int *P1,*P2;P1 = &A;cout<<A<<”:”<<B<<endl;P2 = &B;cout<<A<<”:”<<B<<endl;*P1 += 20;cout<<A<<”:”<<B<<endl;Present

*P2 += *P1;Prcout<<A<<”:”<<B<<endl;esent

P1 = P2;cout<<A<<”:”<<B<<endl;*P1 = 20;cout<<A<<”:”<<B<<endl;cout<<A<<”:”<<B<<endl; 15

Page 16: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output ?

16

int A = 5, B = 15;int *P1,*P2; P1 = &A; //1P2 = &B; //2*P1 += 20; //3*P2 += *P1;//4P1 = P2; //5*P1 = 20; //6cout<<A<<”:”<<B<<endl;

P1

5

15

P2 B

A1

2

P1

25A

3

40P2 B

4

P1

5 20B

P1

P2

6

Page 17: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointers: Data types● Every pointer points to an item of some data

type.● The exception is void*. A generic pointer,

pointing to any data type.● But, void* can not be dereferenced, ● So z = *x; is invalid when x is void*.

17

Page 18: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Why Pointers ?● Dynamic Memory allocation: Creating variables

on a heap, location of the newly created variable is returned as a pointer to the variable.

● Function Calls: Function calls use call-by-value. A function ``copies’’ its parameters and modifies this local copy. In order to modify values of parameters, we pass its location, i.e., a pointer to the function.

18

Page 19: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dynamic Memory Allocation

● Variables are created using new/malloc○ int* x = (int*)malloc(sizeof(int)); // C○ int* x = new int; // C++

● A pointer, i.e., memory location of the variable is returned.

19

Page 20: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dynamic Memory Allocation

● Variables explicitly created must be explicitly killed.○ free(x);//C○ delete(x);//C++

● Pass a pointer to the memory location in heap where the variable resides.

20

Page 21: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Beware if you don’t.● If variables created in the heap are not explicitly

freed… they stay, causing a memory leak.

● So be careful to ensure that every malloc is paired with

a free, and every new is paired with a delete.

21

Page 22: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Memory Leakvoid doSomething(){ int *P = new int; //integer allocated dynamically} //not de-allocated (freed).

When the function ends, P will go out of scope. Hence no more references to the dynamically allocated memory, causing memory leak.int Value = 5;int *P = new int;P = &Value; //Old address LOST, results in memory LEAK

22

Page 23: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Quiz

23

Page 24: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?void FREEME(int* x) { … free(x); }int* x = (int*)malloc(sizeof(int));FREEME(x);free(x);

24

Page 25: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?int* ALLOC() {int* x = (int*)malloc(sizeof(int));return x;

}:p=ALLOC();p=ALLOC();p=ALLOC();...

25

Page 26: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Function Calls

● Parameters passed use call-by-value.○ foo(int x, char y) {... }

foo(A,B);■ Copy of x and y created within foo.

● To modify parameter values within a function, pass reference, or pointer to variable.

26

Page 27: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Passing pointers to functions.swap(int x, int y) {int t;t = x;

x = y; y = t;}

27

.

.

.swap (a,b)...

Page 28: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Passing pointers to functions.swap(int x, int y) {int t;t = x;

x = y; y = t;}

28

swap(int* x, int* y){int t;t = *x;

*x = *y; *y = t;}

Page 29: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Passing pointers to functions.swap(int* x, int* y) {int *t;t = x;

x = y; y = t;}

29

.

.

.swap(&a, &b);...

Page 30: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Passing pointers to functions.swap(int &x, int &y) {int t;t = x;

x = y; y = t;}

30

.

.

.swap(a, b);...

Page 31: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Quiz

31

Page 32: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?int f(int x, int* y) {int t = x;

x += 1; *y = t;} ...int a=10,b=20;f(a,&b); cout<<a<<“ “<<b<<endl; 32

10 10

Page 33: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?int f(int x, int* y) {int t = x;

x += 1; *y = t;} :f(a,&b); // a, acout<<a<<“ “<<b<<endl; 33

Page 34: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointer Arithmetic

● A pointer is an address, which is a numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value.

● Arithmetic operators which can be used on pointers are:

++, --, +, and -34

Page 35: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointers and Arrays● Closely related.● Array name is a constant pointer to the first

element.● A[0] is equivalent to *A● A[1] is equivalent to *(A+1)● A[2] is equivalent to *(A+2) and so on.

35

Page 36: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointer to an Array - Example 1int A[4]={12,56,78,89};int *Ptr;Ptr=A;//1cout << *(Ptr+1) << endl;Ptr++;//2cout<<*Ptr<<endl;(*Ptr)+=10;cout<<A[1]<<endl;

36

Ptr

A[0] A[1] A[2] A[4]

12 56 78 89

Ptr

A[0] A[1] A[2] A[4]

12 56 78 89

1

2

Page 37: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Quiz

37

Page 38: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output ?int A[]={10,20,30,40,50};int *Ptr = A;for (int i = 0; i< 5; i++)

cout << *Ptr++ << " "; cout<<endl;Ptr = A;for (i = 0;i < 4; i++,Ptr++) cout << ++*Ptr << " "; cout << endl;for (i = 0;i < 5; i++) cout <<A[i]<< " ";

38

Page 39: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output ?int A[]={10,20,30,40,50};int *Ptr = A;for (int i = 0; i< 5; i++)

cout << *Ptr++ << " "; //10 20 30 40 50cout<<endl;Ptr = A;for (i = 0;i < 4; i++,Ptr++) cout << ++*Ptr << " "; //11 21 31 41cout << endl;for (i = 0;i < 5; i++) cout <<A[i]<< " "; //11 21 31 41 50

39

Page 40: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Character PointersString: array of characters, delimited by ‘\0’.char *Str,Txt[20]=”GetUp”;Str=Txt;cout<<*Str<<” “ << Str<<endl;Str++;*Str=’o’;cout<<Txt<<endl;

40

Page 41: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Character pointers

char a[] = “Hello World”;char *p = “Welcome to IIIT”;

The first is an array holding Hello World. The second is a pointer. p can be modified to pointsomewhere else later in the program. Not a.

41

Page 42: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Quiz

42

Page 43: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

What is the output?void Strlen(char* s) {

int n;for(int n = 0; *s != ‘\0’; ++n);return n;

}cout<<strlen(“hello world”);// string constantcout<<strlen(array); // char array[1000];cout<<strlen(ptr); // char* ptr;

43

Page 44: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointers and ConstantsPointer to a constantconst char* Ptr = &A;//1

char* const Ptr = &A;//2

const char* const Ptr = &A;//3

44

Page 45: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointer to a constant character

char A=’C’;char B=’D’;const char * Ptr = &A;//1*Ptr=B;//Error, can not change *PtrPtr=&B;//Correctcout<<*Ptr<<endl;

45

Declares a pointer to a

constant character.

Page 46: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Constant pointer to charchar A=’C’;char B=’D’;char * const Ptr = &A;//2Ptr=&B;//Error, can not change ptr*Ptr=B;//Correctcout<<*Ptr<<endl;

46

Declares a constant

pointer to a character.

Page 47: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Constant Pointers to Constant charchar A=’C’;char B=’D’;const char * const Ptr = &A;//3*Ptr=B;//Error, can not change *PtrPtr=&B;//Error, can not change ptr

47

Declares a pointer to a character where both the pointer content and the value being

pointed at will not change.

Page 48: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Pointers: Questions

48

Page 49: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Array of Pointersint *A[3];for (int C=0;C<3;C++) A[C]=new int;for (C=0;C<3;C++) *A[C]=30*C;for (C=2;C>=0;C--) cout<<*A[C]<<”:”;:for (C=0;C<3;C++) delete(A[C]);

49

A[0] A[1] A[2]

# # #

*A[0]

0

*A[1]

30

*A[2]

60

Page 50: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

2-D Dynamic Array Allocationint** A;A = (int**)malloc(sizeof(int*)*M);for(int i = 0; i < M; ++i)

A[i] = (int*)malloc(sizeof(int)*N);

50De-a

llocate?

int **A;A = new int*;for(int i = 0; i < M; ++i)

A[i] = new int;

Page 51: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

De-allocate

for(j = 0; j < M; ++j) free(A[j]);

free(A);

51

for(j = 0; j < M; ++j) delete(A[j]);

delete(A);

Page 52: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Function Pointers.

● Functions are not variables. However, we can create pointers to functions.

● Useful in writing generic code (eg: sort)C Quick sort:● int qsort(void* v[], int left, int right,

int (*comp)(void*, void*))

52

Page 53: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Function Pointers● int qsort(void* v[], int left, int right,

int (*comp)(void*, void*))○ Sort an array of any type - from indices left to right.○ Use function pointed to by (*comp) for comparision.○ The function returns an int, and takes two pointers as

parameters.○ Usage: if((*comp)(v[i], v[j]) < 0) {... }

Note: The parantheses are essential.

53

Page 54: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Linked Lists

54

Page 55: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Linked List

● Dynamic Data Structure● Collection of nodes● Each node contains DATA and a POINTER

to the next node.● Types of Lists: Single or Double or Circular.

55

Page 56: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Singly Linked List

24 |Arun |3500

56

24 |Arun |3500 28 |John |4500 37|Ahmad |3500 X

NODE

DATA LINKEDADDRESS

struct NODE{ int Mno; char Name[20]; float Fees; NODE *Link;};

Page 57: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Doubly Linked List

24 |Arun |3500

57

24 |Arun |3500 28 |John |4500 37|Ahmad |3500 X

NODE

DATA LINKEDADDRESS SUCC

struct NODE{ int Mno; char Name[20]; float Fees; NODE *Prev, *Succ; };

LINKEDADDRESS PREV

Page 58: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Array vs Linked ListArray: ● Memory is allocated in contiguous blocks. ● Retrieval of elements from constant set of

elements. ● Insertions and deletions not memory efficient.Linked List● Memory is allocated as per requirement. ● Insertions and deletions is memory efficient.

58

Page 59: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Arrays vs Linked List

Linked List● Accessing easy at the start and end of a

linked list.● Difficult to access elements at arbitrary

positions. Might require traversing the entire list.

59

Page 60: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

QuestionN people standingin a circle.Every 2nd isREJECTED as LEADERstarting from the 1st.

Who lives ? (Becomes LEADER)

12

3

4

n

60

Page 61: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Question

Values for some n:

61

1 2 3 4 5 6 7 8 8 10

1 1 3 1 3 5 7 1 3 5

11 12 13 14 15 16 17 18 19 20

7 9 11 13 15 1

Page 62: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Question

Implementation: Use circular linked list.Create a node with label 1 with successor pointing to itself.

62

1

Page 63: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Questionwhile( x != x->next) {for(i = 1; i < M; ++i)

x = x->next; // count M.x->next = x->next->next; N--;

// Delete node.}

63

Page 64: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Question

● We could instead do the following:○ Let k = ⌊log2 N⌋○ return 2*( N - 2k) + 1.

● Compute the survivor without running the whole algorithm !

64

Page 65: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Question

● Suppose N = 2k for some k.● Then, after the first round, we have 2(k-1)

survivors, and the gun is back to Player 1.● Now, it follows by induction.

65

Page 66: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Question

● Suppose N = 2k + m, m < 2k

● Then, after m people have been shot, the gun is with player number 2m+1.

● At this point, there are 2k players left, and by the earlier argument, this guy survives.

66

Page 67: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Linked List

Write the code to reverse a singly linked list.

67

Page 68: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Linked Listvoid REVERSE(Node** Start){ Node* Prev= NULL,Cur=*Start, Next; while (Cur != NULL) { Next = Cur->next; Cur->next = Prev; Prev = Cur; Cur = Next; } *Start = Prev;}

345 ->

765 ->

450 ->

134 ->

Start

68

Page 69: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Linked Listvoid REVERSE(Node** Start){ Node* Prev= NULL,Cur=*Start, Next; while (Cur != NULL) { Next = Cur->next; Cur->next = Prev; Prev = Cur; Cur = Next; } *Start = Prev;}

345 ->

765 ->

450 ->

134 ->

StartCur

Next

1

2

3

Prev4

Cur5

69

Page 70: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Stack and Queue

70

Page 71: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Stacks and Queues

● Stack : Last In First Out (LIFO)● Queue : First In First Out (FIFO)● Deque : Insert and Delete at both ends.

Very useful DATA STRUCTURES in many algorithmic problems.

71

Page 72: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dynamic Stack

struct NODE{ int Bno; char Title[20]; NODE *Link;};

72

class STACK{ NODE *Top;public: STACK(); void PUSH(); void POP(); ~STACK();};

Page 73: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Stack::PUSH(){ NODE *T; T=new NODE; cin>>T->Bno; gets(T->Title); T->Link=Top; Top=T;}

Dynamic Stack

73

Stack::Stack(){Top=NULL;}

24 |Modern PhysicsT

Top X

24 |Modern Physics XTop

24 |Modern Physics XTop

31|Fast TrackT

24 |Modern Physics X

Top 31|Fast Track

Page 74: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Stack::POP(){ if (Top!=NULL) { NODE *T=Top; cout<<T->Bno; cout<<T->Title; Top=Top->Link; delete T; }}

Dynamic Stack

74

24 |Modern Physics X

Top31|Fast Track

T

24 |Modern Physics XTop

24 |Modern Physics XTop

T

Top X

Page 75: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Stack::~Stack(){ while (Top!=NULL) { NODE *T=Top; Top=Top->Link; delete T; }}

Dynamic Stack

75

void main(){ Stack S;char CH; do { cout<<”P:Push O:Pop” <<”Q:Quit ”; cin>>CH; switch(CH) { case ‘P’:S.Push(); break; case ‘P’:S.Pop(); } } while (CH!=’Q’);}

Page 76: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Queue: Implementation

● We can implement a queue using an array or linked list.

● If we do not know the size of the queue, a linked list implementation is prefered.

76

Page 77: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Linked Implementation of a Queue ● Allocate memory for each new element dynamically

● Link the queue elements together

● Use two pointers, Front and Rear, to mark the front

and rear of the queue

77

Page 78: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dynamic Queue

78

struct NODE{ int Pno; char Passenger[20]; NODE *Link;};

class QUEUE{ NODE *R,*F;public: QUEUE(); void INSERT(); void DELETE(); ~QUEUE();};

Page 79: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dynamic Queuing

79

QUEUE::INSERT(){ NODE *T; T=new NODE; cin>>T->Pno; gets(T->Passenger); T->Link=NULL; if (R!=NULL) R=F=T; else { R->Link=T;R=T;}}

QUEUE::QUEUE(){R=F=NULL;}

24 |Ravi Sahai XT

R F X

24 |Ravi Sahai XR F

42 |John Kerry XT

24 |Ravi SahaiR F

42 |John Kerry X

F 24 |Ravi Sahai

R

Page 80: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Dynamic Queuing

80

QUEUE::DELETE(){ if (F!=NULL) { NODE *T=F; cout<<T->Pno; cout<<T->Passenger; F=F->Link; delete T; if (R!=NULL) R=NULL; } }

42 |John Kery XT R F

XR F

42 |John Kerry X

T 24 |Ravi Sahai

R F

42 |John Kerry X

T F 24 |Ravi Sahai

R

42 |John Kery XT

Page 81: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Queue: Applications

● Processor scheduling.

● Graph traversal: BFS.

81

Page 82: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Queue: ApplicationProcessor AllocationP1: Process 1 P2: Process 2P3: Process 3

82

P1P2P3

Page 83: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Six degrees of separation

● Everyone in the world is connected to every one else by at most six degrees.

● We can reach from anyone to anyone else in at most 6 hops.

● Stanley Milgram in the 1970s. Tried this experiment.

● Is this true on Facebook ?83

Page 84: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Graph Traversal: BFS

84

1

3

2

4

5

6

Page 85: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

BFS

● Connected components● Shortest paths● Testing bipartiteness.● And many others...

85

Page 86: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Stacks: Application

● Expression evaluation

● Graph traversal: Depth first search.

86

Page 87: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Expression Evaluation

● Infix: [3/(2 + 5)] * [4/(1 + 2)]● Convert Infix to Postfix using a stack.● Evaluate Postfix notation using a stack.● Postfix: 3 / 5 2 + 4/ 2 1 + *

87

Page 88: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Expression Evaluation

● Convert Infix to PostfixIf ( p = operand) write to output.If (p = `(`) push to stack.If (p = operator) pop all ops of higher precedence and push p to stack.If (p = `)`) pop until `(` .

88

Page 89: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Expression Evaluation.

● To evaluate a postfix expression, again use a stack.

● Scan expression from Left to Right. ○ If(p = operand) push into stack.○ If(p = operator) pop top two elements, evaluate and

push back.

89

Page 90: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

DFS

● Connected Components● Topological searching.● Two connectivity.● Detecting bridges● Finding your way out of a maze.● Generating mazes.

90

Page 91: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Graph Traversal: DFS

91

1

3

2

4

5

6

Page 92: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad puzzles

● Stacks and Queues precede Computer Science.

● Used on railroads to arrange train compartments and route trains.

● We will see some puzzles involving trains and railroads: We assume that all train lines are one-way.

92

Page 93: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad puzzle 1: Queue

● What permutations can we get from a queue?

● What if we are also allowed to bypass the queue?

● How do we implement the queue using railroads ?

93

Page 94: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 1: Queue

94

Page 95: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 1: Queue

● Interleave two increasing permutations:● 14253, 1324, 4321, 321,...

95

Page 96: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad puzzle 2

● How do we implement a stack using railroads ?

● What permutations can we obtain using a stack?

96

Page 97: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad puzzle 2: Stack

3412

97

Page 98: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad puzzle 2: Stack

412 3

98

Page 99: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 2: Stacks

Can we obtain all permutations?

1

23

21 3

2

1

2

3

3 1

3 1 2

3 2 199

Page 100: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 2: Stacks

Can we obtain all permutations?

1

23

21 3

2

1

2

3

3 1

3 1 2

3 2 1 100

Page 101: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad puzzle 2: Stacks

● Find a permutation of railcars that can not be obtained using a stack.

● Is there a characterization of permutations that can be obtained using a stack ?

101

Page 102: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 3

How do we represent a deque using rail tracks?Recall: A deque is a double-ended queue.

102

Page 103: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 3

103

Page 104: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 3Can every permutation be obtained using deques ?

104

Page 105: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 3

52341, 25341, 42351, 24351,

105

Page 106: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Railroad Puzzle 4

● How many moves are required for the trains to pass each other if only one carriage or engine can fit into the siding?

106

Page 107: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Summary● Pointers are variables that store memory

locations.● Pointers have a type - telling us the type of

the object at the memory location pointed to.● Two operations with pointers: &(reference:

what is the memory location of this variable?) and *(what is stored at the memory location pointed to by the pointer variable) 107

Page 108: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Summary

● Useful in building dynamic data structures - structures whose size is not known at compile time.

● Objects in the heap need to be created and freed explicitly. Creation returns a pointer to the object.

● Need to be careful to free/delete the object after use. 108

Page 109: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Summary

● Linked List: Fundamental data structure to store elements, enabling INSERT, DELETE, SEARCH.

● INSERT and DELETE are quick (with pointer to location)

● SEARCH for an arbitrary element is slow.

109

Page 110: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Summary● Stacks and Queues are fundamental data

structures with many applications in CS (and outside CS).

● Applications: Scheduling, Parsing, Graph traversal, and some puzzles with trains leading to very nice mathematical questions… some of which are still unanswered!

110

Page 111: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

References.

● For the railroad puzzles:

● ``Trains of thought’’, Brian Hayes, American Scientist, Vol. 95, No. 2, 2007.

111

Page 112: Dynamic Data Structures - Indraprastha Institute of ... Pointers ? Dynamic Memory allocation: Creating variables on a heap, location of the newly created variable is returned as a

Thank you

112

Rajiv RamanMukesh Kumar | Monica Sahni | Menika Anand | Rajesh Sethi | Anju Gupta

csamazingresources.blogspot.in(Developed as a part of IIITD Workshop for CS Teachers on 16-Aug-2015)