U3.stack queue

Post on 15-Jan-2015

687 views 1 download

Tags:

description

U3.stack queue

transcript

Stacks

What is a stack? Stores a set of elements in a particular order Stack principle: LAST IN FIRST OUT = LIFO It means: the last element inserted is the first

one to be removed Example Which is the first element to pick up?

Last In First Out

BA

DCBA

CBA

DCBA

EDCBA

top

top

top

toptop

A

Stack Applications

Real life Pile of books, files, plates TOH

More applications related to computer science stack Program execution Evaluating expressions Palindrome finder Parentheses matcher

A Palindrome is a string that reads the same in either direction Examples: “Able was I ere I saw Elba”

objects: a finite ordered list with zero or more elements. methods: Stack createS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size Boolean isFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) return TRUE else return FALSE Stack push(stack, item) ::= if (IsFull(stack)) stack_full else insert item into top of stack and return

Stack

Boolean isEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSEElement pop(stack) ::= if(IsEmpty(stack)) return else remove and return the item on the top of the stack.

Stack (cont’d)

Array-based Stack Implementation Allocate an array of some size (pre-defined)

Maximum N elements in stack Bottom stack element stored at element 0 last index in the array is the top Increment top when one element is pushed,

decrement after pop

Chapter 5: Stacks8

Stack Implementation #include <stdio.h> #include<conio.h> # define MAXSIZE 200

int stack[MAXSIZE]; int top; //index pointing to the top of stack void main() { void push(int); int pop(); int will=1,i,num; clrscr();

while(will ==1) { printf(" MAIN MENU:\n 1.Add element to stack\n2.Delete element from the

stack"); scanf("%d",&will);

Chapter 5: Stacks9

switch(will) { case 1: printf("Enter the data... "); scanf("%d",&num); push(num); break; case 2: i=pop(); printf("Value returned from pop function is %d ",i); break; default: printf("Invalid Choice . "); }

printf(" Do you want to do more operations on Stack ( 1 for yes, any other key to exit) ");

scanf("%d" , &will); } //end of outer while } //end of main

Chapter 5: Stacks10

void push(int y) {

if(top>MAXSIZE) { printf("\nSTACK FULL"); return; } else { top++; stack[top]=y; } }

Chapter 5: Stacks11

int pop() { int a; if(top<=0) { printf("STACK EMPTY "); return 0; } else { a=stack[top]; top--; } return(a);

}

The Towers of HanoiA Stack-based Application

GIVEN: three poles a set of discs on the first pole, discs of different sizes,

the smallest discs at the top GOAL: move all the discs from the left pole to the right

one. CONDITIONS: only one disc may be moved at a time. A disc can be placed either on an empty pole or on top

of a larger disc.

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi

Towers of Hanoi

Chapter 5: Stacks21

Polish(prefix) notation - * / 15 - 7 + 1 1 3 + 2 + 1 1 = - * / 15 - 7 2 3 + 2 + 1 1 = - * / 15 5 3 + 2 + 1 1 = - * 3 3 + 2 + 1 1 = - 9 + 2 + 1 1 = - 9 + 2 2 = - 9 4 = 5

An equivalent in-fix is as follows: ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5

STACK OPERATIONSREVERSE POLISH NOTATION (postfix) Reverse polish notation :is a postfix

notation (places operators after operands)

(Example) Infix notation A + BReverse Polish notation AB+ also called postfix.

STACK OPERATIONSREVERSE POLISH NOTATION (postfix) A stack organization is very effective for

evaluating arithmetic expressions

A * B + C * D (AB *)+(CD *) AB * CD * +

( 3 * 4 ) + ( 5 * 6 ) 34 * 56 * +

STACK OPERATIONSREVERSE POLISH NOTATION (postfix)n • Evaluation procedure:

n 1. Scan the expression from left to right.2. When an operator is reached, perform the operation with the two operands found on the left side of the operator.3. Replace the two operands and the operator by the result obtained from the operation.

n (Example) infix 3 * 4 + 5 * 6 = 42 postfix 3 4 * 5 6 * +

n 12 5 6 * +12 30 +42

STACK OPERATIONSREVERSE POLISH NOTATION (postfix) • Reverse Polish notation evaluation with a stack.

Stack is the most efficient way for evaluating arithmetic expressions.

stack evaluation:Get valueIf value is data: push dataElse if value is operation: pop, pop evaluate and push.

STACK OPERATIONSREVERSE POLISH NOTATION (postfix)

(Example) using stacks to do this. 3 * 4 + 5 * 6 = 42

=> 3 4 * 5 6 * +

27

Queue

The Queue Operations

A queue is like a line of people waiting for a bank teller. The queue has a front and a rear.

$ $

FrontRear

The Queue Operations

New people must enter the queue at the rear. The C++ queue class calls this a push, although it is usually called an enqueue operation. $ $

FrontRear

The Queue Operations

When an item is taken from the queue, it always comes from the front. The C++ queue calls this a pop, although it is usually called a dequeue operation. $ $

FrontRear

The Queue Class

The C++ standard template library has a queue template class.

The template parameter is the type of the items that can be put in the queue.

template <class Item>class queue<Item>{public: queue( ); void push(const Item& entry); void pop( ); bool empty( ) const; Item front( ) const; …

};

Array Implementation A queue can be implemented with an array,

as shown here. For example, this queue contains the integers 4 (at the front), 8 and 6 (at the rear).

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .

An array of integers to implement a queue of integers

4 8 6

We don't care what's inthis part of the array.

Array Implementation

The easiest implementation also keeps track of the number of items in the queue and the index of the first element (at the front of the queue), the last element (at the rear).

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .

4 8 6

size3

first0

last2

A Dequeue Operation

When an element leaves the queue, size is decremented, and first changes, too.

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .

4 8 6

size2

first1

last2

An Enqueue Operation

When an element enters the queue, size is incremented, and last changes, too.

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .

28 6

size3

first1

last3

At the End of the Array

There is special behavior at the end of the array. For example, suppose we want to add a new element to this queue, where the last index is [5]:

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ]

2 16

size3

first3

last5

At the End of the Array

The new element goes at the front of the array (if that spot isn’t already used):

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ]

2 16

size4

first3

last0

4

Array Implementation

Easy to implement But it has a limited capacity with a fixed

array Or you must use a dynamic array for an

unbounded capacity Special behavior is needed when the

rear reaches the end of the array.

[ 0 ] [1] [ 2 ] [ 3 ] [ 4 ] [ 5 ] . . .

4 8 6

size3

first0

last2

Linked List Implementation

10

15

7

null

13

A queue can also be implemented with a linked list with both a head and a tail pointer.

head_ptr

tail_ptr

Linked List Implementation

10

15

7

null

13

Which end do you think is the front of the queue? Why?

head_ptr

tail_ptr

Linked List Implementation

10

15

7

nullhead_ptr

13

The head_ptr points to the front of the list.

Because it is harder to remove items from the tail of the list.

tail_ptr

Front

Rear

Priority Queues42

A priority queue is a container in which access or deletion is of the highest-priority item, according to some way of Assigning priorities to items.

Priority Queues43

FOR EXAMPLE, SUPPOSE A HOSPITAL

EMERGENCY ROOM HAS THE

FOLLOWING FOUR PATIENTS, WITH

NAME, PRIORITY, AND INJURY:

Priority Queues44

Matt 20 sprained ankle Andrew 45 broken leg Samira 20 high blood pressure Kerem 83 heart attack IN WHAT ORDER SHOULD THE

PATIENTS BE TREATED?

Priority Queues45

THERE ARE MANY APPLICATIONS

OF PRIORITY QUEUES, IN AREAS AS

DIVERSE AS SCHEDULING, DATA

COMPRESSION, AND JPEG (Joint

Photographic Experts Group) ENCODING.

Using Priority Queue to Track Your Assignments Organize class or work assignments by due

dates Early due date, higher priority diagram of class Assignment