Docsity

Memory Organization, Queues - Data Stuctures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Memory Organization, Queues - Data Stuctures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Memory Organization

Code

Static data

Stack

Heap

Process 1

(browser)

Process 3

(word)

Process 4

(excel)

Windows OS

Process 2

(dev-c++)

Stack Layout during a call

 Here is stack layout when function F calls

function G:

Parameters(F)

Local variables(F)

Return address(F)

Parameters(G)

Parameters(F)

Local variables(F)

Return address(F)

Parameters(F)

Local variables(F)

Return address(F)

Parameters(G)

Local variables(G)

Return address(G)

At point of call During execution of G After call

sp

sp

sp

Queue Operations

Enqueue(X) – place X at the rear of the

queue.

Dequeue() -- remove the front element and

return it.

Front() -- return front element without

removing it.

IsEmpty() -- return TRUE if queue is

empty, FALSE otherwise

Implementing Queue

 Using linked List: Recall

 Insert works in constant time for either end

of a linked list.

 Remove works in constant time only.

 Seems best that head of the linked list be

the front of the queue so that all removes

will be from the front.

 Inserts will be at the end of the list.

Implementing Queue

 Using linked List:

front

front rear

rear

front

front rear

rear

dequeue()

Implementing Queue

 Using linked List:

front

front rear

rear

front

front rear

rear

enqueue(9)

Implementing Queue

int front()

return front->get();

int isEmpty()

return ( front == NULL );

Queue using Array

 If we use an array to hold queue elements,

both insertions and removal at the front

(start) of the array are expensive.

 This is because we may have to shift up to

“n” elements.

 For the stack, we needed only one end; for

queue we need both.

 To get around this, we will not shift upon

removal of an element.

Queue using Array

front

rear

front

rear

enqueue(6)

Queue using Array

front

rear

front

rear

enqueue(8)

Queue using Array

front

rear

front

rear

dequeue()

Queue using Array

front

rear

front

rear

enqueue(9)

enqueue(12)

enqueue(21) ??

Queue using Array

 Basic idea is to picture the array as a

circular array.

front

rear

front

rear

Queue using Array

void enqueue(int x)

{

rear = (rear+1)%size;

array[rear] = x;

noElements = noElements+1;

}

front

rear

front

rear

enqueue(21)

size

noElements