Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

§3 The Stack ADT 1. ADT A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are.
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Lec 7 Sept 17 Finish discussion of stack infix to postfix conversion Queue queue ADT implementation of insert, delete etc. an application of queue.
More on Stacks and Queues. As we mentioned before, two common introductory Abstract Data Type (ADT) that worth studying are Stack and Queue Many problems.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
CSCE 3110 Data Structures & Algorithm Analysis Queues Reading: Chap. 3 Weiss.
E.G.M. Petrakislists, stacks, queues1 Stacks Stack: restricted variant of list –Elements may by inserted or deleted from only one end  LIFO lists –Top:
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
 Balancing Symbols 3. Applications
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Doubly-Linked Lists Same basic functions operate on list Each node has a forward and backward link: What advantages does a doubly-linked list offer? 88.
Stack and Queue COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks and Queues COMP171 Fall Stack and Queue / Slide 2 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Lecture 8 Feb 19 Goals: l applications of stack l Postfix expression evaluation l Convert infix to postfix l possibly start discussing queue.
Chapter 3. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be.
Stacks CS 308 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Lecture 11 Sept 26, 2011 Goals convert from infix to postfix.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
CS Data Structures Chapter 3 Stacks and Queues.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Data Structure Dr. Mohamed Khafagy. Stacks Stack: what is it? ADT Applications Implementation(s)
Stack Data Structure By : Imam M Shofi. What is stack? A stack is a limited version of an array. A stack is a limited version of an array. New elements,
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Chapter 3: Stacks And Queues
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Stacks Chapter 8. Objectives In this chapter, you will: Learn about stacks Examine various stack operations Learn how to implement a stack as an array.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Stacks Stack is a data structure that can be used to store data which can later be retrieved in the reverse or last in first out (LIFO) order. Stack is.
Queues Linear list. One end is called front. Other end is called rear. Additions are done at the rear only. Removals are made from the front only. FIFO.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Chap 3 Stack and Queue. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable.
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
Stacks Stacks.
Homework 4 questions???.
Stack and Queue APURBO DATTA.
Stacks Stack: restricted variant of list
Stacks Chapter 4.
Algorithms and Data Structures
Visit for more Learning Resources
Stack.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Instructor: Mr.Vahidipour
CSC 143 Stacks [Chapter 6].
Stack A data structure in which elements are inserted and removed only at one end (called the top). Enforces Last-In-First-Out (LIFO) Uses of Stacks Evaluating.
پشته ها و صف ها.
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks and Queues 1.
Stacks.
Stacks CS-240 Dick Steflik.
Stack.
CH3. STACKS AND QUEUES.
Presentation transcript:

Chapter 3 1

Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated to any data type, irrespective of whether this data type is a fundamental C++ type or a user- defined type. 2

Selection sort using templates 3 template void SelectionSort ( T *a, const int n ) {// Sort a[0] to a[n-1] into nondecreasing order. for ( int i = 0 ; i < n ; i++ ) { int j = i; // find smallest integer in a[i] to a[n-1] for ( int k = i + 1 ; k < n ; k++ ) if ( a[k] < a[j] ) j = k; swap ( a[i], a[j] ); } }

Code fragment illustration template instantiation float farray [ 100 ]; int intarray [ 250 ];.. // assume that the arrays are initialized at this point SelectionSort ( farray, 100 ); SelectionSort ( intarray, 250 ); 4

Stack Last-In-First-Out (LIFO) list Push Add an element into a stack Pop Get and delete an element from a stack 5 pushpop

System stack after function call 6

Abstract data type Stack template class Stack { // A finite ordered list with zero or more elements public: Stack (int stackCapacity = 10); // Create an empty stack whose initial capacity is stackCapacity bool IsEmpty ( ) const; // if empty, return true; else, return false. T& Top ( ) const; // Return top element of stack. void Push (const T& item); // Insert item into the top of the stack. void Pop ( ); // Delete the top element of the stack. }; 7

Implementation private: int top; T *stack; int capacity; template Stack ::Stack(int stackCapacity): MaxSize(stackCapacity) { stack=new T[capacity]; top=-1; } 8

template inline Boolean Stack ::IsFull() { if (top==capacity-1) return TRUE; else return FALSE; } template inline Boolean Stack ::IsEmpty() { if (top==-1) return TRUE; else return FALSE; } 9

Adding to a stack template void Stack ::Push (const T& x) { // Add x to the stack. if (top = = capacity – 1) { ChangeSize1D (stack, capacity, 2 * capacity); capacity *= 2; } stack [ ++top ] = x; } 10

Deleting from a stack template void Stack ::Pop ( ) { // Delete top element from the stack. if (IsEmpty ( ) ) throw “Stack is empty. Cannot delete.”; stack [ top-- ].~T(); // destructor for T } 11

Queue First-In-First-Out (FIFO) list Add an element into a queue Get and delete an element from a queue Variation Priority queue 12 A AB ABC ABCD ABCDE BCDE ↑ ↑↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ f, r fr f r f r f r f r add delete f = queue front r = queue rear

Abstract data type Queue template class Queue { public: Queue (int queueCapacity = 10); // Create an empty queue whose initial capacity is stackCapacity bool IsEmpty ( ) const; // If empty, return true; else, return false. T& Front ( ) const; // Return the element at the front of the queue. T& Rear ( ) const; // Return the element at the rear of the queue. void Push (const T& item); // Insert item at the rear of the queue. void Pop ( ); // Delete the front element of the queue. } ; 13

Implementation private: int front,rear; T *queue; int capacity; template Queue ::Queue(int queueCapacity):capacity(queueCapacity) { queue=new T[capacity]; front=rear= 0; } 14

template inline Boolean Queue ::IsFull() { if (rear==capacity-1) return TRUE; else return FALSE; } template inline Boolean Stack ::IsEmpty() { if (front==rear) return TRUE; else return FALSE; } 15

Circular queue Two indices front: one position clockwise from the first element rear: current end 16

Adding to a queue template void Queue ::Push(const& x); { // Add x at rear of queue. if ((rear + 1) % capacity = = front) { // queue full, double capacity // omit } rear = (rear + 1) % capcity; queue [rear ] = x; } 17

Deleting from a queue template void Queue ::Pop( ); { // Delete front element from queue. if (IsEmpty( )) throw "Queue is empty. Cannot delete."; front = (front + 1) % capacity; queue [front ]. ̃T(); // destructor for T } 18

Problem: if front=rear? 19 Increase the capacity of a queue just before it become full

A mazing problem 20 0: path1: block

Allowable moves 21

Data type move struct offsets { int a,b; }; enum directions{ N, NE, E, SE, S, SW, W, NW}; offsets move[8]; 22

Table of moves qmove[q ].amove[q ].b N −1 0 NE −1 1 E 0 1 SE 1 1 S 1 0 SW 1−1 W 0 NW −1 23

Implementation with a stack A maze is represented by a two dimensional array maze[m][p] struct Items{ int x, y, dir; }; 24

Example in → →out Stack (x,y,dir) PositionAction (1,1)Mark (1,1) (1,1,2)(1,2)Mark (1,2) (1,2,2) (1,1,2) (1,3)Mark (1,3) (1,3,2) (1,2,2) (1,1,2) (1,4)Mark (1,4) ……… 25 Stack (x,y,dir) PositionAction (1,4,4) (1,3,2) (1,2,2) (1,1,2) (2,4)Mark (2,4) ……… (2,4,6) (1,4,4) (1,3,2) (1,2,2) (1,1,2) (2,3)Mark (2,3) (1,4,4) (1,3,2) (1,2,2) (1,1,2) (2,4)pop

Example in → →out Stack (x,y,dir) PositionAction (1,3,2) (1,2,2) (1,1,2) (1,4)pop (1,2,2) (1,1,2) (1,3)pop (1,1,2)(1,2)pop (1,2,5) (1,1,2) (2,1)Mark (2,1) ……… 26

First pass at finding a path through a maze Initialize list to the maze entrance coordinates and direction east; while (list is not empty) { (i, j, dir) = coordinates and direction from end of list; delete last element of list; while (there are more moves from (i, j) ) { (g, h) = next move; if ((g = = m) && (h = = p)) sucess; if ((!maze [g][h]) // legal move && (!mark [g][h])) // haven’t been here before { mark [g ][h] = 1; dir = next direction to try; add (i, j, dir) to end of list; (i, j, dir) = (g, h, N) ; } } } cout << "No path in maze." << endl; 27

Finding a path through a maze void Path(const int m, const int p) { // start at (1, 1) mark[1][1] = 1; Stack stack(m*p); Items temp(1, 1, E); // set temp.x, temp.y, and temp.dir Stack.Push(temp); while (!stack.IsEmpty( )) { 28

temp = stack.Top( ); stack.Pop( ); int i = temp.x; int j = temp.y; int d = temp.dir; while (d < 8) // move forward { int g = i + move[d].a; int h = j + move[d].b; if ((g = = m) && (h = = p)) { // reached exit // output path cout << stack; cout << i << " " << j << endl; cout << m << " " << p << endl; return; } if ((!maze [g ][h]) && (!mark [g ][h])) { // new position mark[g][h] = 1; temp.x = i; temp.y = j; temp.dir = d+1; stack.Push(temp); // stack it i = g; j = h; d = N; // move to (g, h) else d++; // try next direction } } cout << "No path in maze." << endl; } 29

Evaluation of expressions X = a / b - c + d * e - a * c Suppose that a = 4, b = 2, c = 2, d =3, e = 3 Interpretation 1: ((4/2)-2)+(3*3)-(4*2)= =1 Interpretation 2: (4/(2-2+3))*(3-4)*2=(4/3)*(-1)*2= … How to generate the machine instructions corresponding to a given expression? Precedence rule + associative rule 30

Priority of operators in C++ 31 PriorityOperator 1unary minus, ! 2*, /, % 3+, - 4 =, > 5= =, != 6&& 7||

Evaluation of expressions Infix Each operator comes in-between the operands Eg. 2+3 Postfix Each operator appears after its operands Eg. 23+ Prefix Each operator appears before its operands Eg

Example InfixPostfix 2+3*4234*+ a*b+5ab*5+ (1+2)*712+7* a*b/cab*c/ (a/(b-c+d))*(e-a)*cabc-d+/ea-*c* a/b-c+d*e-a*cab/c-de*ac*-+ 33

Example: 6/2-3+4*2  62/3-42*+ 34 TokenStack [0] [1] [2] Top 62/3-42*+62/3-42* /2 6/2 3 6/2-3 6/ / /2-3 4*2 6/2-3+4*

Evaluating postfix expressions void Eval(Expression e) {// Assume that the last token in e is ‘#’ // NextToken is used to get the next token from e Stack stack; // initialize stack for (Token x = NextToken(e); x!= ‘#’; x=NextToken(e)) if (x is an operand) stack.Push(x) // add to stack else {// operator remove the correct number of operands for operator x from stack; perform the operation x and store the result onto the stack; } 35

Infix to postfix (1) Fully parenthesize expression a / b - c + d * e - a * c  ((((a / b) - c) + (d * e)) – (a * c)) (2) All operators replace their corresponding right parentheses. ((((a / b) - c) + (d * e)) - a * c)) (3) Delete all parentheses. ab/c-de*+ac*- 36

Example: a+b*c 37 TokenStack [0] [1] [2] TopOutput a + b * c eos + + * 0 1 a ab abc abc*+

Example: a*b+c 38 TokenStack [0] [1] [2] TopOutput a * b + c eos **++** a ab ab* ab*c ab*c+

Example: a*(b+c)*d 39 TokenStack [0] [1] [2] TopOutput a * ( b + c ) * d eos * * ( * ( + * a ab abc abc+ abc+* abc+*d abc+*d*