Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 2 INTRODUCTION TO STACKS 【 Problem 】 Read an integer n,which will be at most 25,then read a list of n numbers,and print the list in reverse order.

Similar presentations


Presentation on theme: "CHAPTER 2 INTRODUCTION TO STACKS 【 Problem 】 Read an integer n,which will be at most 25,then read a list of n numbers,and print the list in reverse order."— Presentation transcript:

1

2 CHAPTER 2 INTRODUCTION TO STACKS 【 Problem 】 Read an integer n,which will be at most 25,then read a list of n numbers,and print the list in reverse order. Read an integer n,which will be at most 25,then read a list of n numbers,and print the list in reverse order.

3 CHAPTER 2 INTRODUCTION TO STACKS 【 学习内容 】 【 学习内容 】 BASIC CONCEPTS 1. Stack Specifications 2. Implementation of Stacks 3. Application: A Desk Calculator 4. Application: Bracket Matching 5. Abstract Data Types and Their Implementations

4 Stacks  A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. The last entry which is inserted is the first one that will be removed.

5 Last in,first out (LIFO) Push and Pop

6 §2.1 The Stack Abstract Data Type A stack is a Last-In-First-Out (LIFO) list, that is, an ordered list in which insertions and deletions are made at the top only. 1 2 3 4 5 6 65 6 5 〖 Example 〗 System Stack Return Address Stack Frame s p Local Variables Return Address s p Old Frame Pointer s p f p s p f p

7  The standard template library (abbreviated STL) in C++ contains much useful information, many functions, and many classes.  We can include the STL stack implementation into our programs with the directive #include  and then we can then initially empty stack objects and apply methods called push, pop, top, and empty. Standard Template Library (STL)

8  In C++, a template construction allows us to create data structures whose entries have different types. Example: stack numbers  The STL provides several implementations of various data structures such as stacks.  A second, optional template parameter selects the implementation. Standard Template Library (STL)

9 First Example: Reversing a List

10 2.2 IMPLEMENTATION OF STACKS  顺序栈 Contiguous Stack  链栈 Linked Stack Use classes to implement the data structures. Thus,we shall now develop a class Stack whose data members represent the entries of a stack.

11 2.2.1 Specification of Method for Stacks  Stack methods:  empty()  top()  push()  pop()

12 1.Constructor

13  For generality, we use Stack entry for the type of entries in a Stack. A client can specify this type with a definition such as typedef int Stack_entry;or typedef char Stack_entry;  The ability to use the same underlying data structure and operations for different entry types is called generics. typedef provides simple generics. Starting in Chapter 6, we shall use C++ templates for greater generality. 2.Entry Types, Generics

14  We shall use a single enumerated type called Error_code to report errors from all of our programs and functions.  The enumerated type Error code is part of the utility package in Appendix C. Stacks use three values of an Error_code: success, overflow, underflow  Later, we shall use several further values of an Error code. 3.Error Processing

15 4. Specification for Methods structure Stack is objects: A finite ordered list with zero or more elements. Error code Stack :: 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 and the Stack is left unchanged. Error code Stack :: 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 Stack :: top(Stack entry &item) const; Pre: None. Post: The top of a nonempty Stack is copied to item. A code of fail is returned if the Stack is empty. bool Stack :: empty( ) const; Pre: None. Post: A result of true is returned if the Stack is empty, otherwise false is returned.

16 2.2.2 Class Specification ------ Contiguous Stack

17 Representation of Data in a Contiguous Stack

18 Stack Methods

19 Further Stack Methods

20 #include template class Stack { private: int top; // 栈顶指针 Type *elements; // 栈元素数组 int maxSize; // 栈最大容量 无计算器的栈的数组存储表示 0 1 2 3 4 5 6 7 8 9 maxSize-1 栈空 top ( 栈空 ) elements

21 public: Stack (int sz = 10); // 构造函数 ~Stack ( ) { delete [ ] elements; } void Push (Type x); // 进栈 int Pop (Type& x); // 出栈 int GetTop (Type& x); // 取栈顶 void MakeEmpty ( ) { top = - 1; } // 置空栈 int IsEmpty ( ) const { return top == - 1; } int IsFull ( ) const { return top == maxSize - 1; } }

22 top 空栈 top a 进栈 b 进栈 aa b a b c d e e 进栈 a b c d e f 进栈溢出 a b d e e 退栈 c

23 top c 退栈 b 退栈 a b a a 退栈 空栈空栈 top a b d d 退栈 c top a b c

24 Reverse Polish Calculator In a Reverse Polish calculator, the operands (numbers, usually) are entered before an operation (like addition, subtraction, multiplication, or division) is specified. The operands are pushed onto a stack. When an operation is performed, it pops its operands from the stack and pushes its result back onto the stack.

25 表达式求值 一个表达式由操作数 ( 亦称运算对象 ) 、操作符 ( 亦称运算符 ) 和分界符组成。 一个表达式由操作数 ( 亦称运算对象 ) 、操作符 ( 亦称运算符 ) 和分界符组成。 算术表达式有三种表示: 算术表达式有三种表示:  中缀 (infix) 表示 , ,如 A+B ;  前缀 (prefix) 表示 ,如 +AB ;  后缀 (postfix) 表示 ,如 AB+ ;

26 例如 : Exp = a  b + (c  d / e)  f 前缀式 : +  a b   c / d e f 中缀式 : a  b + c  d / e  f 后缀式 : a b  c d e /  f  + 结论 : 1 )操作数之间的相对次序不变 ; 2 )运算符的相对次序不同 ; 3 )中缀式丢失了括弧信息, 致使运算的次序不确定 ; 4) 前缀式的运算规则为 : 连续出现的两个操作数和在它们 之前且紧靠它们的运算符构成一 个最小表达式 ; 5) 后缀式的运算规则为 : 运算符在式中出现的顺序恰为 表达式的运算顺序 ; 每个运算符和在它之前出现 且 紧靠它的两个操作数构成一个最小 表达式 ;

27 如何从后缀式求值? 先找运算符, 再找操作数 例如: a b  c d e /  f  + abab d/ed/e c-d/e (c-d/e)  f

28  ? : denote an instruction to read an operand and push it onto the stack;  +,-,*,/: represent arithmetic operations;  = :is an instruction to print the top of the stack(but not pop it off) 

29 Obtaining a Command The auxiliary function get command obtains a command from the user, checking that it is valid and converting it to lowercase by using the string function tolower( ) that is declared in the standard header le cctype.

30

31  Programs written in C++ contain several different types of brackets.For example , brackets are used to enclose expressions,function arguments,array indices,and blocks of code.  The brackets used within a program must pair off.  For example,the following string  {a=(1+v(b[3+c[4]]))  {a=(b[0)+1];} Application: Bracket Matching

32 括号匹配的检验 假设在表达式中 ([]())或[([ ][ ])] 等为正确的格式, [( ])或([( ))或 (( )]) 均为不正确的格式。 则 检验括号是否匹配的方法可用 “ 期待的急迫程度 ” 这个概念来描述。

33 分析可能出现的不匹配的情况 :  到来的右括弧非是所 “ 期待 ” 的 ; 例如:考虑下列括号序列: [ ( [ ] [ ] ) ] 1 2 3 4 5 6 7 8  到来的是 “ 不速之客 ”;  直到结束,也没有到来所 “ 期待 ” 的括弧 ;

34 Bracket Matching  We develop a program to check that brackets are correctly matched in an input text file.  We limit our attention to the brackets {, }, (, ), [, and ].  We read a single line of characters and ignore all input other than bracket characters.  Algorithm: Read the program file character by character. Each opening bracket (, [, or { that is encountered is considered as unmatched and is stored until a matching bracket can be found. Any closing bracket ), ], or } must correspond, in bracket style, to the last unmatched opening bracket, which should now be retrieved and removed from storage. Finally, at the end of the program, we must check that no unmatched opening brackets are left over.

35 算法的设计思想: 1 )凡出现左括弧,则进栈; 2 )凡出现右括弧,首先检查栈是否空 若栈空,则表明该 “ 右括弧 ” 多余 否则和栈顶元素比较, 若相匹配,则 “ 左括弧出栈 ” 否则表明不匹配 3 )表达式检验结束时, 若栈空,则表明表达式中匹配正确 否则表明 “ 左括弧 ” 有余

36 Bracket Matching Program

37  DEFINITION A type is a set, and the elements of the set are called the values of the type.  DEFINITION A sequence of length 0 is empty. A sequence of length n>=1of elements from a set T is an ordered pair ( S n− 1, t) where S n− 1 is a sequence of length n−1 of elements from T, and t is an element of T.  We shall always draw a careful distinction between the word sequential, meaning that the elements form a sequence, and the word contiguous, which we take to mean that the elements have adjacent addresses in memory. Hence we shall be able to speak of a sequential list in a contiguous implementation. Abstract data type

38  DEFINITION A stack of elements of type T is a nite sequence of elements of T, together with the following operations: 1. Create the stack, leaving it empty. 2. Test whether the stack is Empty. 3. Push a new entry onto the top of the stack, provided the stack is not full. 4. Pop the entry off the top of the stack, provided the stack is not empty. 5. Retrieve the Top entry from the stack, provided the stack is not empty. Abstract Stack

39 1. On the abstract level we decide how the data are related to each other and what operations are needed, but we decide nothing concerning how the data will actually be stored or how the operations will actually be done. 2. On the data structures level we specify enough detail so that we can analyze the behavior of the methods and make appropriate choices as dictated by our problem. 3. On the implementation level we decide the details of how the data structures will be represented in computer memory. 4. On the application level we settle all details required for our particular application. The first two levels are often called conceptual because at these levels we are more concerned with problem solving than with programming. The middle two levels can be called algorithmic because they concern precise methods for representing data and operating with it. The last two levels are specifically concerned with programming. Refinement of Data Specification

40 Homework  P56 Exercises 2.1 E1(a)(d), E2,E3, E4(b)  P2.2 Exercises 2.2 top E1(int top=>count), E2, E3(a)(b)(d), E4  P69 Programming project 2.3 P2, P4


Download ppt "CHAPTER 2 INTRODUCTION TO STACKS 【 Problem 】 Read an integer n,which will be at most 25,then read a list of n numbers,and print the list in reverse order."

Similar presentations


Ads by Google