SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Chapter 3 Stacks and Queues 3.1 Templates in C++ 3.2 The Stack Abstract Data Type 3.3 The Queue Abstract Data Type 3.4 Subtyping and Inheritance in C++ 3.5 A Mazing Problem 3.6 Evaluation of Expressions 3.7 Multiple Stacks and Queues
3.1 Templates in C++ ,[object Object],3.1.1 Templates Functions ,[object Object]
A template may 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.
template  又稱為  parameterized type.
3.1 Templates in C++ template  < class  KeyType> void  sort(KeyType *a,  int  n) {  //  作非遞減排序 for  ( int  i = 0; i < n; i++) { int  j = i; for  ( int  k = i + 1; k < n; k++)   // 找出最小元素位置 if  (a[k] < a[ j]) j = k;  KeyType temp = a[i]; a[i] = a[j]; a[j] = temp; } }  // Program 3.1 Selection sort using templates
3.1 Templates in C++ float  farray[100]; int  intarray[250]; ... sort(farray, 100); sort(intarray, 250); ,[object Object]
若  KeyType  是基本資料結構,則如此寫已足夠;若是  KeyType  是程式設計者自訂的資料結構,就需要針對  <  作運算子重載,也需要對  =  作運算子重載或給  copy constructor 。
3.1 Templates in C++ 3.1.2 Using Templates to Represent Container Classes ,[object Object],template  < class  Type> class  Bag { public : Bag( int  MaxSize = DefaultSize); ~Bag(); void  Add( const  Type&); Type *Delete(Type&); Boolean IsFull(); Boolean IsEmpty(); private : void  Full(); void  Emplty(); Type *array; int  MaxSize; int  top; };
3.1 Templates in C++ template  < class  Type> Bag<Type>::Bag( int  MaxBagSize): MaxSize(MaxBagSize) { array =  new  Type[MaxSize]; top = -1; } template  < class  Type> Bag<Type>::~Bag() { delete  [] array; } template  < class  Type> void  Bag<Type>::Add( const  Type& x) { if (IsFull()) Full(); else  array[++top] = x; }  // 定義在類別外面的成員函式,每一個函式都加上  template <class Type> 宣告方法 Bag < int > a(3); Bag <Rectangle> r(10);
D A B C 3.2 The Stack Abstract Data Type ,[object Object]
Stack : Last-In-First-Out(LIFO) list
A  stack  is an ordered list in which insertions and deletions are made at one end called the  top .  例如:插入  A,B,C,D ,刪除一個元素。
令  S = (a 0 , a 1 , ..., a n-1 ) , a 0  is bottom, a n-1  is top, a i  is on top of a i-1 , 0 < i < n.
3.2 The Stack Abstract Data Type ,[object Object],fp main previous frame pointer return address local variables fp a1
3.2 The Stack Abstract Data Type template  < class   KeyType> class  Stack {  // objects: A finite ordered list of zero or more elements public : Stack ( int  MaxStackSize = DefaultSize); Boolean IsFull();  // return TRUE if Stack is full; FALSE otherwise Boolean IsEmpty();  // return TRUE if Stack is empty; FALSE otherwise void  Add(const  KeyType &); // if IsFull(), return 0;  // else insert an element to the top of the Stack KeyType  *Delete( KeyType &);  // if IsEmpty(), then return 0; // else remove and return a pointer to the top element };  // Abstract data type Stack , member function  的部份
3.2 The Stack Abstract Data Type template  < class   KeyType> class  Stack{  // data member  的部份 ... private : int   top; KeyType  *stack; int   MaxSize; }; template  < class   KeyType>  // 建構子 Stack <KeyType> :: Stack  ( int  MaxStackSize):MaxSize(MaxStackSize) {  stack =  new   KeyType [MaxSize]; top = -1; }
3.2 The Stack Abstract Data Type template  < class   KeyType > inline  Boolean Stack< KeyType >:: IsFull (){  if (top == MaxSize – 1)  return  TRUE;  else   return  FALSE; } template  < class   KeyType > inline  Boolean Stack< KeyType >:: IsEmpty (){  if  (top == -1)  return  TRUE;  else   return  FALSE;  }
3.2 The Stack Abstract Data Type template  < class   KeyType> void  Stack< KeyType >:: Add ( const   KeyType& x ){  // add x to stack if ( IsFull() ) StackFull(); else  stack[++top] =  x ;  } template  < class  KeyType> KeyType* Stack<Keytype>:: Delete (KeyType& x) {  // Remove top element from stack  if  (IsEmpty() ) { StackEmpty(); return  0;} x  = stack[top--];  return ( & x  ); }
Exercises 3.2  2. Consider the railroad switching network given in Figure 3.3. Raidroad cars numbered 1, 2, 3, ..., n are initially in the top right track segment (in this order, left to right). Railroad cars can be moved into the vertical track segment one at a time from either of the horizontal segments and then moved from the vertical segment to any one of the horizontal segments. The vertical segment operates as a stack as new cars enter at the top and cars depart the vertical segment from the top. For instance, if n = 3, we could move car 1 into the vertical segment, move 2 in, move 3 in, and then take the cars out producing the new order 3, 2, 1. For n = 3 and 4 what are the possible permutations of the cars that can be obtained? Are any permutations not possible ?
3.3 The Queue Abstract Data Type ,[object Object]
First-In-First-Out (FIFO)
Example  ,[object Object]
a 0  is the front element, a n-1  is the rear element,
a i  is behind a i-1 , 1  ≤  i  ≤  n. B C D E A f r r r r r f
3.3 The Queue Abstract Data Type ,[object Object]
資料成員: private : int  front, rear; KeyType *queue; int  MaxSize; ,[object Object],template  < class  KeyType> Queue<KeyType>:: Queue ( int  Max):MaxSize(Max) { queue =  new  KeyType[MaxSize]; front = rear = -1; }
3.3 The Queue Abstract Data Type ,[object Object],template  < class  KeyType> inline  Boolean Queue<KeyType>:: IsFull () { if  (rear == MaxSize – 1)  return  TRUE; else   return  FALSE; }  // 未必真的滿,因  front  很可能大於  -1 template  < class  KeyType> inline  Boolean Queue<KeyType>:: IsEmpty () { if (front == rear)  return  TRUE; else   return  FALSE; }
3.3 The Queue Abstract Data Type ,[object Object],template  < class  KeyType> void  Queue<KeyType>:: Add ( const  KeyType& x) { if  (IsFull()) QueueFull(); else  queue[++rear] = x; } template  < class  KeyType> KeyType* Queue<KeyType>:: Delete (KeyType& x) { if (IsEmpty()) {QueueEmpty();  return  0;} x = queue[++front]; return  x; }
3.3 The Queue Abstract Data Type Figure 3.5 Insertion and deletion from a queue front  rear  Q[0]  [1]  [2]  [3]  [4]  [5]  [6]...  Comments -1  -1  queue  empty  initial -1  0 J1   J1 joins Q -1 1 J1  J2   J2 joins Q -1  2 J1  J2  J3   J3 joins Q 0 2   J2  J3   J1 leaves Q 0  3  J2  J3  J4   J4 joins Q 1 3  J3  J4   J2 leaves Q front  rear  Q[0]  [1]  [2]  ...... [n-1]   Next Operation -1  n-1  J1  J2  J3  ......  Jn initial state 0  n-1   J2  J3  ......  Jn delete J1 -1 n-1   J2  J3  J4  ......  Jn+1 add Jn+1   (J2 through   Jn are moved) 0  n-1   J3  J4  ......  Jn+1 delete J2 -1 n-1   J3  J4  J5  ......  Jn+2 add Jn+2 Figure 3.6 Queue example
3.3 The Queue Abstract Data Type ,[object Object],J4 J3 J2 J1 [4] [3] [2] [1] [0] [n-1] [n-2] [n-3] [n-4] [n-5] front = 0, rear = 4 J4 J3 J2 J1 [4] [3] [2] [1] [0] [n-1] [n-2] [n-3] [n-4] [n-5] front = n-4, rear = 0
3.3 The Queue Abstract Data Type ,[object Object],template  < class   KeyType > void  Queue< KeyType >:: Add  ( const   KeyType& x ) // add x to the circular queue { int   newrear=(rear+1)% MaxSize; if  ( front == newrear)  QueueFull(); else   queue[rear = newrear] =  x ; }  //  先用餘數運算算出新的  rear  值。 ,[object Object]
3.3 The Queue Abstract Data Type ,[object Object],template  < class   KeyType > KeyType  *Queue< KeyType >:: Delete  ( KeyType &  x ) // remove front element from queue { if  ( front == rear ) {  QueueEmpty(); return 0; } front = (front + 1) % MaxSize; x  = queue[front];  return  & x ; } ,[object Object]
3.4 Subtyping and Inheritance in C++ ,[object Object]
A data object of Type B IS- A data object of Type A if B is more specialized than A or A is more general than B. The set of all objects of Type B is a subset of the set of all objects of Type A.
例如:椅子是家具、獅子是哺乳動物、矩形是多邊形
Stack IS-A Bag or Stack is a subtype of Bag.
C++ provides a mechanism to express the IS-A relationship called  public inheritance .
class  Stack: public  Bag {  // Bag  是  base class, Stack  是  derived class Stack( int  MaxSize = DefaultSize); ~Stack(); int * Delete( int &); }
3.4 Subtyping and Inheritance in C++ class  Bag { public : Bag( int  MaxSize = DefaultSize); virtual  ~Bag(); virtual   void  Add( int ); virtual   int * Delete( int &); virtual  Boolean IsFull(); virtual  Boolean IsEmpty(); protected : virtual   void  Full(); virtual   void  Empty(); int  *array, MaxSize, top; }; class  Stack:  public  Bag {  Stack( int  MaxSize = DefaultSize); ~Stack(); int * Delete( int &); }
3.4 Subtyping and Inheritance in C++ ,[object Object]
Another important consequence of public inheritance is that inherited members have the same level of access in the derived class as they did in the base class. Stack::Stack ( int  MaxStackSize) :Bag(MaxStackSize) { } Stack::~Stack() { }  //  直接呼叫  Bag  的解構子 int * Stack::Delete( int & x) { if  (IsEmpty()) {Empty();  return  0;} x = array[top--]; return  &x; }
3.4 Subtyping and Inheritance in C++ Bag b(3); Stack s(3);  //Stack  裡面的建構子 b.Add(1); b.Add(2); b.Add(3);  // 使用 Bag::Add s.Add(1); s.Add(2); s.Add(3);  // 使用 Bag::Add int  x; b.Delete(x);  // 呼叫 Bag::Delete s.Delete(x); // 呼叫 Stack::Delete ,使用 Bag::IsEmpty, Bag::Empty ,[object Object]
3.5 Amazing Problem ,[object Object]
多訓練幾次,可算出老鼠的學習曲線。
可用程式來模擬,只是理論上,程式應該第二次就可以將完全正確的路徑記起來。 entrance  exit
3.5 Amazing Problem ,[object Object],[object Object]
maze[i][j] = 0  代表可走的路徑
maze[i][j] = 1  代表不可走的路徑 , blocked path
maze[1][1]  是入口 (entrance) ,而  maze[m][p]  是出口 (exit) ,[object Object]
3.5 Amazing Problem X 西北 NW 北 N 東北 NE 東 E 東南 S E 南 S 西南 SW 西 W [ i – 1 ][ j – 1 ] [ i - 1 ][ j ] [ i - 1 ][ j + 1 ] [ i ][ j + 1 ] [ i + 1 ][ j + 1 ] [ i + 1 ][ j ] [ i + 1 ][ j – 1 ] [ i ][ j – 1 ] [ i ][ j ]

Weitere ähnliche Inhalte

Was ist angesagt?

Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoJoel Falcou
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddumaneesh boddu
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Philip Schwarz
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexityIntro C# Book
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)adsRavi Rao
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 englishssuser442080
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
Preparation Data Structures 07 stacks
Preparation Data Structures 07 stacksPreparation Data Structures 07 stacks
Preparation Data Structures 07 stacksAndres Mendez-Vazquez
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 

Was ist angesagt? (20)

Lesson 5 link list
Lesson 5  link listLesson 5  link list
Lesson 5 link list
 
Chapter 7 ds
Chapter 7 dsChapter 7 ds
Chapter 7 ds
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.Proto
 
Data Structures by Maneesh Boddu
Data Structures by Maneesh BodduData Structures by Maneesh Boddu
Data Structures by Maneesh Boddu
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
 
C sharp chap5
C sharp chap5C sharp chap5
C sharp chap5
 
Stack Algorithm
Stack AlgorithmStack Algorithm
Stack Algorithm
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
Python basics
Python basicsPython basics
Python basics
 
(Recursion)ads
(Recursion)ads(Recursion)ads
(Recursion)ads
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Preparation Data Structures 07 stacks
Preparation Data Structures 07 stacksPreparation Data Structures 07 stacks
Preparation Data Structures 07 stacks
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 

Andere mochten auch

教會改用Open office的經驗
教會改用Open office的經驗教會改用Open office的經驗
教會改用Open office的經驗春男 洪
 
資料結構平常測驗一的解答
資料結構平常測驗一的解答資料結構平常測驗一的解答
資料結構平常測驗一的解答春男 洪
 
資料結構平常測驗
資料結構平常測驗資料結構平常測驗
資料結構平常測驗春男 洪
 
Preparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_typesPreparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_typesAndres Mendez-Vazquez
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleHitesh Kumar
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
4.4 Set operations on relations
4.4 Set operations on relations4.4 Set operations on relations
4.4 Set operations on relationsJan Plaza
 
Creating an Abstract Data Type in C++
Creating an Abstract Data Type in C++Creating an Abstract Data Type in C++
Creating an Abstract Data Type in C++Dennis Gajo
 

Andere mochten auch (16)

教會改用Open office的經驗
教會改用Open office的經驗教會改用Open office的經驗
教會改用Open office的經驗
 
資料結構平常測驗一的解答
資料結構平常測驗一的解答資料結構平常測驗一的解答
資料結構平常測驗一的解答
 
Section1-1
Section1-1Section1-1
Section1-1
 
資料結構平常測驗
資料結構平常測驗資料結構平常測驗
資料結構平常測驗
 
Chapter01
Chapter01Chapter01
Chapter01
 
Lec3
Lec3Lec3
Lec3
 
Preparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_typesPreparation Data Structures 03 abstract data_types
Preparation Data Structures 03 abstract data_types
 
Algo>Abstract data type
Algo>Abstract data typeAlgo>Abstract data type
Algo>Abstract data type
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Queue in C, Queue Real Life of Example
Queue in C, Queue Real Life of ExampleQueue in C, Queue Real Life of Example
Queue in C, Queue Real Life of Example
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil1. Fundamental Concept - Data Structures using C++ by Varsha Patil
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
 
4.4 Set operations on relations
4.4 Set operations on relations4.4 Set operations on relations
4.4 Set operations on relations
 
Inpact 2012 presentation
Inpact 2012 presentationInpact 2012 presentation
Inpact 2012 presentation
 
Creating an Abstract Data Type in C++
Creating an Abstract Data Type in C++Creating an Abstract Data Type in C++
Creating an Abstract Data Type in C++
 

Ähnlich wie Chapter03

Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptOliverKane3
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arraystameemyousaf
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 
computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8ecomputernotes
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfdhavalbl38
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notesGOKULKANNANMMECLECTC
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docxadkinspaige22
 

Ähnlich wie Chapter03 (20)

Ch03_stacks_and_queues.ppt
Ch03_stacks_and_queues.pptCh03_stacks_and_queues.ppt
Ch03_stacks_and_queues.ppt
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
computer notes - Data Structures - 8
computer notes - Data Structures - 8computer notes - Data Structures - 8
computer notes - Data Structures - 8
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Templates
TemplatesTemplates
Templates
 
Lecture5
Lecture5Lecture5
Lecture5
 
Templates2
Templates2Templates2
Templates2
 
2 a stacks
2 a stacks2 a stacks
2 a stacks
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Overloading
OverloadingOverloading
Overloading
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
 
05 queues
05 queues05 queues
05 queues
 
Lesson 4 stacks and queues
Lesson 4  stacks and queuesLesson 4  stacks and queues
Lesson 4 stacks and queues
 

Kürzlich hochgeladen

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Kürzlich hochgeladen (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Chapter03

  • 1. Chapter 3 Stacks and Queues 3.1 Templates in C++ 3.2 The Stack Abstract Data Type 3.3 The Queue Abstract Data Type 3.4 Subtyping and Inheritance in C++ 3.5 A Mazing Problem 3.6 Evaluation of Expressions 3.7 Multiple Stacks and Queues
  • 2.
  • 3. A template may 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.
  • 4. template 又稱為 parameterized type.
  • 5. 3.1 Templates in C++ template < class KeyType> void sort(KeyType *a, int n) { // 作非遞減排序 for ( int i = 0; i < n; i++) { int j = i; for ( int k = i + 1; k < n; k++) // 找出最小元素位置 if (a[k] < a[ j]) j = k; KeyType temp = a[i]; a[i] = a[j]; a[j] = temp; } } // Program 3.1 Selection sort using templates
  • 6.
  • 7. 若 KeyType 是基本資料結構,則如此寫已足夠;若是 KeyType 是程式設計者自訂的資料結構,就需要針對 < 作運算子重載,也需要對 = 作運算子重載或給 copy constructor 。
  • 8.
  • 9. 3.1 Templates in C++ template < class Type> Bag<Type>::Bag( int MaxBagSize): MaxSize(MaxBagSize) { array = new Type[MaxSize]; top = -1; } template < class Type> Bag<Type>::~Bag() { delete [] array; } template < class Type> void Bag<Type>::Add( const Type& x) { if (IsFull()) Full(); else array[++top] = x; } // 定義在類別外面的成員函式,每一個函式都加上 template <class Type> 宣告方法 Bag < int > a(3); Bag <Rectangle> r(10);
  • 10.
  • 12. A stack is an ordered list in which insertions and deletions are made at one end called the top . 例如:插入 A,B,C,D ,刪除一個元素。
  • 13. 令 S = (a 0 , a 1 , ..., a n-1 ) , a 0 is bottom, a n-1 is top, a i is on top of a i-1 , 0 < i < n.
  • 14.
  • 15. 3.2 The Stack Abstract Data Type template < class KeyType> class Stack { // objects: A finite ordered list of zero or more elements public : Stack ( int MaxStackSize = DefaultSize); Boolean IsFull(); // return TRUE if Stack is full; FALSE otherwise Boolean IsEmpty(); // return TRUE if Stack is empty; FALSE otherwise void Add(const KeyType &); // if IsFull(), return 0; // else insert an element to the top of the Stack KeyType *Delete( KeyType &); // if IsEmpty(), then return 0; // else remove and return a pointer to the top element }; // Abstract data type Stack , member function 的部份
  • 16. 3.2 The Stack Abstract Data Type template < class KeyType> class Stack{ // data member 的部份 ... private : int top; KeyType *stack; int MaxSize; }; template < class KeyType> // 建構子 Stack <KeyType> :: Stack ( int MaxStackSize):MaxSize(MaxStackSize) { stack = new KeyType [MaxSize]; top = -1; }
  • 17. 3.2 The Stack Abstract Data Type template < class KeyType > inline Boolean Stack< KeyType >:: IsFull (){ if (top == MaxSize – 1) return TRUE; else return FALSE; } template < class KeyType > inline Boolean Stack< KeyType >:: IsEmpty (){ if (top == -1) return TRUE; else return FALSE; }
  • 18. 3.2 The Stack Abstract Data Type template < class KeyType> void Stack< KeyType >:: Add ( const KeyType& x ){ // add x to stack if ( IsFull() ) StackFull(); else stack[++top] = x ; } template < class KeyType> KeyType* Stack<Keytype>:: Delete (KeyType& x) { // Remove top element from stack if (IsEmpty() ) { StackEmpty(); return 0;} x = stack[top--]; return ( & x ); }
  • 19. Exercises 3.2 2. Consider the railroad switching network given in Figure 3.3. Raidroad cars numbered 1, 2, 3, ..., n are initially in the top right track segment (in this order, left to right). Railroad cars can be moved into the vertical track segment one at a time from either of the horizontal segments and then moved from the vertical segment to any one of the horizontal segments. The vertical segment operates as a stack as new cars enter at the top and cars depart the vertical segment from the top. For instance, if n = 3, we could move car 1 into the vertical segment, move 2 in, move 3 in, and then take the cars out producing the new order 3, 2, 1. For n = 3 and 4 what are the possible permutations of the cars that can be obtained? Are any permutations not possible ?
  • 20.
  • 22.
  • 23. a 0 is the front element, a n-1 is the rear element,
  • 24. a i is behind a i-1 , 1 ≤ i ≤ n. B C D E A f r r r r r f
  • 25.
  • 26.
  • 27.
  • 28.
  • 29. 3.3 The Queue Abstract Data Type Figure 3.5 Insertion and deletion from a queue front rear Q[0] [1] [2] [3] [4] [5] [6]... Comments -1 -1 queue empty initial -1 0 J1 J1 joins Q -1 1 J1 J2 J2 joins Q -1 2 J1 J2 J3 J3 joins Q 0 2 J2 J3 J1 leaves Q 0 3 J2 J3 J4 J4 joins Q 1 3 J3 J4 J2 leaves Q front rear Q[0] [1] [2] ...... [n-1] Next Operation -1 n-1 J1 J2 J3 ...... Jn initial state 0 n-1 J2 J3 ...... Jn delete J1 -1 n-1 J2 J3 J4 ...... Jn+1 add Jn+1 (J2 through Jn are moved) 0 n-1 J3 J4 ...... Jn+1 delete J2 -1 n-1 J3 J4 J5 ...... Jn+2 add Jn+2 Figure 3.6 Queue example
  • 30.
  • 31.
  • 32.
  • 33.
  • 34. A data object of Type B IS- A data object of Type A if B is more specialized than A or A is more general than B. The set of all objects of Type B is a subset of the set of all objects of Type A.
  • 36. Stack IS-A Bag or Stack is a subtype of Bag.
  • 37. C++ provides a mechanism to express the IS-A relationship called public inheritance .
  • 38. class Stack: public Bag { // Bag 是 base class, Stack 是 derived class Stack( int MaxSize = DefaultSize); ~Stack(); int * Delete( int &); }
  • 39. 3.4 Subtyping and Inheritance in C++ class Bag { public : Bag( int MaxSize = DefaultSize); virtual ~Bag(); virtual void Add( int ); virtual int * Delete( int &); virtual Boolean IsFull(); virtual Boolean IsEmpty(); protected : virtual void Full(); virtual void Empty(); int *array, MaxSize, top; }; class Stack: public Bag { Stack( int MaxSize = DefaultSize); ~Stack(); int * Delete( int &); }
  • 40.
  • 41. Another important consequence of public inheritance is that inherited members have the same level of access in the derived class as they did in the base class. Stack::Stack ( int MaxStackSize) :Bag(MaxStackSize) { } Stack::~Stack() { } // 直接呼叫 Bag 的解構子 int * Stack::Delete( int & x) { if (IsEmpty()) {Empty(); return 0;} x = array[top--]; return &x; }
  • 42.
  • 43.
  • 46.
  • 47. maze[i][j] = 0 代表可走的路徑
  • 48. maze[i][j] = 1 代表不可走的路徑 , blocked path
  • 49.
  • 50. 3.5 Amazing Problem X 西北 NW 北 N 東北 NE 東 E 東南 S E 南 S 西南 SW 西 W [ i – 1 ][ j – 1 ] [ i - 1 ][ j ] [ i - 1 ][ j + 1 ] [ i ][ j + 1 ] [ i + 1 ][ j + 1 ] [ i + 1 ][ j ] [ i + 1 ][ j – 1 ] [ i ][ j – 1 ] [ i ][ j ]
  • 51. 3.5 Amazing Problem q move[q].a move[q].b N -1 0 NE -1 1 E 0 1 SE 1 1 S 1 0 SW 1 -1 W 0 -1 NW -1 -1
  • 52.
  • 53. 可以用 maze[m+2][p+2] 的陣列來模擬迷宮,最外圈全部都設為 1 ,這樣就不用考慮邊緣的情形。
  • 54.
  • 55. 3.5 Amazing Problem initialize stack to the maze entrance coordinates and direction east; while ( stack is not empty) { ( i , j , dir ) = coordinates and direction deleted from top of stack ; while (there are more moves) { ( g , h ) = coordinates of next move; if (( g == m ) && ( h == p )) success; if (! maze [ g ][ h ]) && (! mark [ g ][ h ]) { // 有路走且尚未走過 mark [ g ][ h ] = 1; dir = next direction to try; add( i , j , dir ) to top of stack ; i = g; j = h; dir = north ; } } } cout << &quot;no path found&quot; << endl;
  • 56.
  • 57. 用 mark[m+2][p+2] 來記錄是否走過, initialize 為 0 ,走過就設為 1
  • 58. maze[1][1] 與 maze[m][p] 都為 0 。
  • 59. 要將前面的演算法實作出來,還需要一個 stack ,這個 stack 最多有 mp 個元素 ( 最長路徑的長度,每個位置都放到 stack 中 ) ,實際上可能沒那麼多,但可能到 m/2 (p – 2) + 2
  • 60. Stack 的每一項可定義如下: struct items { int x, y, dir; };
  • 61. void path( int m, int p) { mark[1][1] = 1; Stack<items> stack(m*p); items temp; temp.x = 1; temp.y = 1; temp.dir = E; stack.Add(temp); while (!stack.IsEmpty()) { temp = *stack.Delete(temp); int i = temp.x; int j = temp.y; int d = temp.dir; while (d < 8) { int g = i + move[d].a; int h = j + move[d].b; if ((g == m) && (h == p)) { cout << stack; cout << i << &quot; &quot; << j << endl; cout << m << &quot; &quot; << p << endl; return ; } if ((!maze[g][h]) && (!mark[g][h])) { mark[g][h] = 1; temp.x = i; temp.y = j; temp.dir = d + 1; stack.Add(temp); i = g; j = h; d = N; } else d++; } } cout << &quot;no path in maze&quot; << endl; }
  • 62.
  • 63. 裡面的 while 迴圈最多跑八次,每次都是 constant time ,因此整個 while 迴圈是 constant time 。
  • 64. 外面的 while 迴圈最多就是每個點都放到 stack 一次,因此 time complexity 就是 O(mp) 。
  • 65. 真正作老鼠走迷宮的實驗時,可以在出口的地方放 cheese ,用以吸引老鼠跑快一點,用電腦模擬如何將這種變因考慮在內呢?有辦法找到最短路徑嗎?
  • 66. 參考習題: 2. What is the maximum path length from start to finish for any maze of dimensions m * p?
  • 67.
  • 68. Operators: +, –, *, /, %, >, < , ==, >=, <=, !=, &&, ||, !, ...
  • 70.
  • 71.
  • 72.
  • 73.
  • 74. Postfix: A B / C – D E * + A C * –
  • 75.
  • 76.
  • 77.
  • 78. 2.Move all operators so that they replace their corresponding right parentheses.
  • 79.
  • 80. 將每個括號裡的部份都改成 postfix ,即為 AB/ C– DE* + AC* –
  • 81.
  • 82.
  • 83.
  • 84. Behaves as an operator with low priority when it is in stack, in-stack priority ( isp ) = 8
  • 85.
  • 87. 將 infix 轉成 postfix 的時間複雜度為 O(n) , n 為 token 數。
  • 88. void postfix(expression e) { Stack<token> stack; token y; stack.Add('#'); for (token x = NextToken(e); x != '#'; x = NextToken(e)) { if (x is an operand) cout << x; else if (x == ')' ) for (y = *stack.Delete(y); y != '('; y = *stack.Delete(y)) cout << y; else { for (y = *stack.Delete(y); isp(y) <= icp(x); y = *stack.Delete(y)) cout << y; stack.Add(y); stack.Add(x); } } while (!stack.IsEmpty()) cout << *stack.Delete(y); }
  • 89.
  • 90. – A + B – C + D
  • 91. A * –B + C
  • 92. (A + B) * D + E / (F + A * D) + C
  • 93. A && B || C || ! (E > F) // 用 C++ 的 precedence
  • 94. !(A && ! ((B < C) || (C > D))) || (C < E)
  • 95.
  • 96. Write an algorithm to evaluate a prefix expression e. (hint: Scan e right to left and assume that the leftmost token of e is '# ')
  • 97. Write an algorithm to transform an infix expression e into its prefix equivalent. Assume that the input expression e begins with a '# ' and that the prefix expression should begin with a '# '.
  • 98.
  • 99. 若有 n 個 stacks 放在同一個陣列,就只好將 M[m] 切成 n 等份,如下圖。 M 0  m/n – 1   2m/n – 1  m – 1 b[0] b[1] b[2] b[n] t[0] t[1] t[2]
  • 100.
  • 101. 3.7 Multiple Stacks and Queues b[0] t[0] b[1] t[1] b[i] t[i] b[i+1] t[i+1] b[i+2] t[j] b[j+1] b[n]