1 / 41

Chapter2 Introduce to Stacks

Chapter2 Introduce to Stacks. Huan Huo. Example. P50 Exercises 2.1 E1 a) ****. 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

yuriddle
Télécharger la présentation

Chapter2 Introduce to Stacks

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter2 Introduce to Stacks Huan Huo Data Structures and Algorithms

  2. Example • P50 Exercises 2.1 E1 a) **** Data Structures and Algorithms

  3. 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? Data Structures and Algorithms

  4. Last In First Out Processing ABCD in a stack top B A C B A D C B A E D C B A D C B A top top top top A Data Structures and Algorithms

  5. Stack Applications • Real life • Pile of books • Plate trays • More applications related to computer science • Program execution stack(例如递归程序的实现) • Evaluating expressions Data Structures and Algorithms

  6. DEFINITION A stack • DEFINITION A stackof elements is a finite sequence, together with the following operations: 1. Create the stack, leaving it empty. 2. Test whether the stack is Empty. 3. Pusha new entry onto the top of the stack, provided the stack is not full. 4. Popthe entry off the top of the stack, provided the stack is not empty. 5. Retrieve the Topentry from the stack, provided the stack is not empty. Data Structures and Algorithms

  7. 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 Data Structures and Algorithms

  8. 1. entry[maxstack].2. countis top.3. All insertions and deletions of items are made at countor count-1. P62 Data Structures and Algorithms

  9. 1. Have one item.2. Push at entry[count]3. Pop at entry[count-1] Data Structures and Algorithms

  10. 1. Have n items.2. Push at entry[count]3. If count>=maxstack Push Then overflow 4. Pop at entry[count-1]5. If count<=0 Pop Then underflow Data Structures and Algorithms

  11. 一个Int栈的实现MyIntStack(.h) enum Error_code{underflow, overflow, success}; const int maxstack= 10; // small value for testing class MyStack { public: MyStack(); bool empty() const; Error_code push(const int &item); Error_code pop(); Error_code top(int &item) const; private: int count; int entry[maxstack]; }; Data Structures and Algorithms

  12. 一个Int栈的实现MyIntStack(.cpp) MyStack::MyStack() /* Pre: None. Post: The stack is initialized to be empty. */ { count = 0; } Data Structures and Algorithms

  13. 一个Int栈的实现MyIntStack(.cpp) bool MyStack::empty() const //can't modify data of class, can't call fuc without const /* Pre: None. Post: If the Stack is empty, true is returned. Otherwise false is returned. */ { bool outcome = true; if (count > 0) outcome = false; return outcome; } Data Structures and Algorithms

  14. 一个Int栈的实现MyIntStack(.cpp) Error_code MyStack::push(const int &item) /* Pre: None. Post: If the Stack is not full, item is added to the top of the Stack. If the Stack is full, an Error_code of overflow is returned and the Stack is left unchanged. */ { Error_code outcome = success; if (count >= maxstack) outcome = overflow; else entry[count++] = item; return outcome; } Put data into array entry entry[i]=item What is i? Data Structures and Algorithms

  15. 一个Int栈的实现MyIntStack(.cpp) Error_code MyStack::pop() /* Pre: None. Post: If the Stack is not empty, the top of the Stack is removed. If the Stack is empty, an Error_code of underflow is returned. */ { Error_code outcome = success; if (count == 0) outcome = underflow; else --count; return outcome; } Data Structures and Algorithms

  16. 一个Int栈的实现MyIntStack(.cpp) Error_code MyStack::top(int &item) const //Read /* Pre: None. Post: If the Stack is not empty, the top of the Stack is returned in item. If the Stack is empty an Error_code of underflow is returned. */ { Error_code outcome = success; if (count == 0) outcome = underflow; else item = entry[count - 1]; return outcome; } Data Structures and Algorithms

  17. 使用上述Int栈实现LIST REVERSE P50 void main() /* Pre: The user supplies an integer n and n decimal numbers. Post: The numbers are printed in reverse order. Uses: The class MyStack and its methods */ { int n; int item; MyStack numbers; // declares and initializes a stack of numbers cout << " Type in an integer n followed by n integer numbers." << endl << " The numbers will be printed in reverse order." << endl; cin >> n; for (int i = 0; i < n; i++) { cin >> item; numbers.push(item); //将item入栈 } cout << endl << endl; while (!numbers.empty()) { numbers.top(item); //访问栈顶元素 cout << item << " "; numbers.pop(); //出栈 } cout << endl; } class MyStack { public: MyStack(); bool empty() const; Error_code push (const int &item); Error_code pop (); Error_code top (int &item) const; private: int count; int entry[maxstack]; }; Data Structures and Algorithms

  18. MyIntStackProgram Data Structures and Algorithms

  19. 通用栈的实现 • Int, Char, Double… • Typedef • Class Templates Data Structures and Algorithms

  20. Typedef typedef double Stack_entry; enum Error_code{underflow, overflow, success}; const int maxstack = 10; // small value for testing class MyStack { public: MyStack(); bool empty() const; Error_code pop(); Error_code top(Stack_entry &item) const; Error_code push(const Stack_entry &item); private: int count; Stack_entry entry[maxstack]; }; Data Structures and Algorithms

  21. MyStackWithTypeDefProgram Data Structures and Algorithms

  22. Templates • Use templates when the code is exactly the same, except for a variable type. • Saves time and coding effort! • C++中支持: • Function Templates • Class Templates Data Structures and Algorithms

  23. Function OverloadC++中,允许两个函数同名,只要其参数表唯一:或者参数个数不同,或者是参数类型不同。 int Abs(int n) { return n<0 ? -n : n ; } double Abs(double n) { return n<0 ? -n : n ; } Data Structures and Algorithms

  24. 实际上,若“提取”出一个可变化的类型参数T,则可“综合”成为如下的同一个函数(模板),它实际上代表着一组函数:实际上,若“提取”出一个可变化的类型参数T,则可“综合”成为如下的同一个函数(模板),它实际上代表着一组函数: T Abs(T n) { return n<0 ? -n : n ; } 在C++中定义完整的函数模板Abs时,格式如下: template <class T> T Abs (T n) { return n<0 ? -n : n; } Data Structures and Algorithms

  25. Template class Definition: template < class type_parameter_list_1,... ,class type_parameter_list_n >return_type template_class_name( parameter list) { function body } Note: 1) type_parameter_list should be used in “return_type”or“parameter list”or“function body”. 2) Invoking is the same,only require the passing the actual parameter。 3) Invoking template class won’t automatic map actual para to formal para. Data Structures and Algorithms

  26. Function Templates template <class Type> Type Abs(Type n) { return n<0 ? -n : n; } int main(){ cout << "Absolute value of -5 is " << Abs(-5); cout << endl; cout << "Absolute value of -5.6 is " << Abs(-5.6); cout << endl; } Data Structures and Algorithms

  27. Assignment • Define a template function max,and implement it with various applications。 • Compare the basic data type and return the biggest one. Data Structures and Algorithms

  28. Class Template:Define a group of classes with the same features, where certain data elements, functions’ parameters and their return values can be any type. Definition of Class Template: template < type formal para or common forma l para spec,... , type formal para or common forma n para spec > class class_template_name{ class body with defined type formal para or common forma l para spec} • type formal para, “class type_formal_name”,i.e. class T //T can be any data type • common formal para,“<type> com_formal_name”,i.e. int length //length can be any value Data Structures and Algorithms

  29. Class Templates enum Error_code{underflow, overflow, success}; const int maxstack = 10; // small value for testing template<class Stack_entry> class MyStack { public: MyStack(); bool empty() const; Error_code push(const Stack_entry &item); Error_code pop(); Error_code top(Stack_entry &item) const; private: int count; Stack_entry entry[maxstack]; }; Data Structures and Algorithms

  30. Class Templates template<class Stack_entry> MyStack<Stack_entry>::MyStack() /* Pre: None. Post: The stack is initialized to be empty. */ { count = 0; } Data Structures and Algorithms

  31. Class Templates template<class Stack_entry> bool MyStack<Stack_entry>::empty() const /* Pre: None. Post: If the Stack is empty, true is returned. Otherwise false is returned. */ { bool outcome = true; if (count > 0) outcome = false; return outcome; } Data Structures and Algorithms

  32. Class template’s function can be claimed either inside or outside the class body. Outside the class body: template < formal para disp. 1,... ,formal para disp. n> Return type class template name< formal para name 1,... ,formal para name n>::function name( formal para list) { ... //fuction body }; “formal para name”comes from“formal para disp.”,utilize the type formal para or common formal para. “class template name< formal para name1,... ,n>::”is class qualifier! Data Structures and Algorithms

  33. 类模板的成员函数既可以在类体内进行说明也可以在类体外进行说明。类模板的成员函数既可以在类体内进行说明也可以在类体外进行说明。 在类体外说明(定义)时使用如下格式: template < 形参1的说明,... ,形参n的说明 > 返回类型 类模板名 < 形参1的名字,... ,形参n的名字 >:: 函数名( 形参表 ) { ... //函数体 }; 上述的“形参1的名字”来自于“形参1的说明”,由“甩掉”说明部分的“类型”而得,是对类型形参或普通形参的使用。 “类模板名 < 形参1的名字,... ,形参n的名字 >::”为在函数名前所加的类限定符! Data Structures and Algorithms

  34. template<class Stack_entry> Error_code MyStack<Stack_entry>::push(const Stack_entry &item) /* Pre: None. Post: If the Stack is not full, item is added to the top of the Stack. If the Stack is full, an Error_code of overflow is returned and the Stack is left unchanged. */ { Error_code outcome = success; if (count >= maxstack) outcome = overflow; else entry[count++] = item; return outcome; } Data Structures and Algorithms

  35. template<class Stack_entry> Error_code MyStack<Stack_entry>::pop() /* Pre: None. Post: If the Stack is not empty, the top of the Stack is removed. If the Stack is empty, an Error_code of underflow is returned. */ { Error_code outcome = success; if (count == 0) outcome = underflow; else --count; return outcome; } Data Structures and Algorithms

  36. template<class Stack_entry> Error_code MyStack<Stack_entry>::top(Stack_entry &item) const /* Pre: None. Post: If the Stack is not empty, the top of the Stack is returned in item. If the Stack is empty an Error_code of underflow is returned. */ { Error_code outcome = success; if (count == 0) outcome = underflow; else item = entry[count - 1]; return outcome; } Data Structures and Algorithms

  37. 使用类模版MyStack实现LIST REVERSE P50 #include "MyStack.cpp" //Attention especially for template void main() { int n; double item; MyStack<double> numbers; // declares and initializes a stack of double numbers cout << " Type in an integer n followed by n decimal numbers." << endl << " The numbers will be printed in reverse order." << endl; cin >> n; for (int i = 0; i < n; i++) { cin >> item; numbers.push(item); } cout << endl << endl; while (!numbers.empty()) { numbers.top(item); cout << item << " "; numbers.pop(); } cout << endl; } Data Structures and Algorithms

  38. When claiming class object with class template,should point out the actual para according to type formal para along with class template name(instantiate a class) class template name< formal para’s actual para1,... ,n> Note:type formal para’s corresponding actual para is type name,while common formal para’s corresponding actual para must be a const。 i.e.: MyStack<double> numbers; Data Structures and Algorithms

  39. 利用类模板说明类对象时,要随类模板名同时给出对应于类型形参或普通形参的具体实参(从而实例化为一个具体的类)。说明格式为:利用类模板说明类对象时,要随类模板名同时给出对应于类型形参或普通形参的具体实参(从而实例化为一个具体的类)。说明格式为: 类模板名 < 形参1的相应实参,... ,形参n的相应实参> 注意:类型形参的相应实参为类型名,而普通形参的相应实参必须为一个常量。 例如: MyStack<double> numbers; Data Structures and Algorithms

  40. MyStackProgram Data Structures and Algorithms

  41. Lab1 • Reading codes: use MyStackto implement P50 LIST REVERSE • DoubleList • MyStack Program • Try to design class template MyArray. • MyArray includes a general type array element. • Implement the retrieve, update operation of index i. • P64 Exercises 2.2 Extended_stack Data Structures and Algorithms

More Related