📄 cdat
字号:
.nr H1 4.oh "The Abstract Data Type" .eh "Stacks".CSSTACKS.CE.NH 2THE ABSTRACT DATA TYPE.LP.spA \fIstack\fR is an ordered listof elements. One end of this list is designated the \fIbottom\fRand the other is called the \fItop\fR. A stack with four elementsis shown in ?F{stack}(a). New elements are always added at the top of thestack. Suppose we wish to add the element \*(LQE\*(ZQ to the stackof ?F{stack}(a). This element will have to be placed on topof the element \*(LQD\*(ZQ giving us the configuration of?F{stack}(b). Deletions from a stack also take place fromthe top only. Hence if we are to delete an element from the stackof ?F{stack}(b), it will be the element \*(LQE\*(ZQ. Followingthe deletion, the configuration of ?F{stack}(a)results. If three successive deletions are performedon the stack of ?F{stack}(b), the stack of ?F{stack}(c)results..KF.hl.TSexpand;l l l. E\(<-@top@ D\(<-@top@ D C C B B B\(<-@top@A\(<-@bottom@ A\(<-@bottom@ A\(<-@bottom@.sp.T&c c c.(a) (b) (c).TE.sp.hl\fB?F{stack}:\fR Stack configurations.KE.ppFrom the preceding discussion, we see that a stackis a LIFO (last in first out) list. Lists of this type appearfrequently in computing.The ADT stack is specified in ADT \n(H1.1..KF.hl\fBADT\fR \fIStack\fR.br{\fBinstances\fR.br.ARordered list of elements; one end is called the \fIbottom\fR;the other is the \fItop\fR;.AL\fBoperations\fR.AR@Create():@ Create an empty stack;.br@IsEmpty():@ Return 0 if stack is empty, return 1 otherwise;.br@IsFull():@ Return 1 if stack is full, return 0 otherwise;.br@Top(x):@ \kQReturn top element of stack in @x@;.br\h'|\nQu'return 0 if the operation fails, return 1 otherwise.br@Add(x):@ \kQAdd element \fIx\fR to the stack;.br\h'|\nQu'return 0 if the operation fails, return 1 otherwise.br@Delete(x):@ \kQDelete top element from stack and return it in \fIx\fR;.br\h'|\nQu'return 0 if the operation fails, return 1 otherwise.AL.AL}.br.hl\fBADT \n(H1.1:\fR The abstract data type stack.KE.oh "Formula-Based Representation".NH 2FORMULA-BASED REPRESENTATION.LP.spSince a stack is a linear list with the restriction that additionsand deletions take place at the same end, we may use the linear listrepresentation of Section 2.3. The top element of the stackis stored in @element[length^-^1]@ and the bottom elementin @element[0]@.The class \fIStack\fR defined in ?P{stackclass} is a derivedclass of @LinearList@ (Program 2.1).The functions \fIAdd\fR and \fIDelete\fR have been implemented by overloadingthe binary operators `+' and `-', respectively. The expression @s~+~x@will add element @x@ to the top of stack @s@ while the expression@s~-~x@ will delete the top element from the stack @s@ and return thedeleted element in variable @x@. Both functions return `0' if they areunable to perform the operation and `1' if the operation is actually performed..KF.hl.nf.ft CWtemplate<class type>class Stack : protected LinearList <type> {// LIFO objectspublic: Stack(int MaxStackSize = 10) : LinearList<type> (MaxStackSize) {} int IsEmpty() {return LinearList<type>::IsEmpty();} int IsFull() {return (Length() == MaxSize);} int Top(type& x) {return Find(Length(), x);} int operator +(type& x) // add x to stack {return Insert(Length(), x);} int operator -(type& x) // delete x from stack {return Delete(Length(), x);}};.ft R.fi.hl\fB?P{stackclass}:\fR Formula-based class \fIStack\fR.KE.uh "Efficiency Of @Stack@".brThe complexity of each of the stack operations is seen to be\(*H(1). Notice thatby deriving @Stack@ from @LinearList@, we have reduced the effort neededto code the class @Stack@. Also, we have significantly improved our chancesof obtaining a correct implementation as the methods for @LinearList@have already been tested and are known to be correct. Unfortunately, thissimplification has come at the cost of increased run time. For example,to add an element to a stack, we first determine its @Length()@ andthen invoke @Insert@ which checks if the insert is in range. Followingthis, a \fBfor\fR loop overhead is paid to perform zero element moves.We can eliminate these overheads by tailoring the code to theclass @Stack@. This can be done by either starting afresh or byaccessing the protected members of @LinearList@ to customize ourcodes..ppAnother potential difficulty is that the derived class @Stack@ is subjectto all of the limitations of the class @LinearList@. For instance,the operations \fBcout\fR and `==' need to be definedon members of the data type @type@ as these are used by the @LinearList@class members @Print@ and @Search@..uh "A Customized Definition of @Stack@".br?P{custom} gives the class definition for @Stack@ when we customizethe @LinearList@ codes. In a run time test which involved a \fBfor\fRwith 100,000 stack add and delete operations, the code of?P{stackclass} took 42% more time than did the customized codeof ?P{custom}. This improvement in performance has however alsocome at some cost..KF.nf.hl.ft CWtemplate<class type>class Stack : protected LinearList <type> {public: Stack(int MaxStackSize = 10) : LinearList<type> (MaxStackSize) {} int IsEmpty() {return LinearList<type>::IsEmpty();} int IsFull() {return (length == MaxSize);} int Top(type& x); int operator +(type& x); // add x to stack int operator -(type& x); // delete x from stack};template<class type>int Stack<type>::Top(type& x){if (IsEmpty()) return 0; //Top failsx = element[length - 1];return 1; //Top succeeds}template<class type>int Stack<type>::operator+(type x){//add x to stackif (IsFull()) return 0; //add failselement[length++] = x;return 1; //add succeeds}template<class type>int Stack<type>::operator-(type& x){//delete top element and return in xif (IsEmpty()) return 0; //delete failsx = element[--length];return 1; //delete succeeds}.hl\fB?P{custom}:\fR Customized version of @Stack@.ft R.fi.KESince the code of ?P{custom} accesses the non-publicmembers of the class @LinearList@ it is prone to failure when changes aremade to @LinearList@ as these changes are required only topreserve the integrity of the public members. This problem can beovercome by extending the class @LinearList@ (Program 2.1)to include public members to add and delete at/from theright end of the list.Another problem is that the code of?P{custom} is somewhat more involved than that of ?P{stackclass}.So,it is expected to take longer to debug..ppThis illustrates some of thetradeoffs involved between software reuse and program efficiency.Interestingly, if we develop the code for the class @Stack@ afresh(i.e., @Stack@ is not derived from @LinearList@ as in ?P{custom}),and perform the run time experiment described above, the new code runs13% faster than the customized code of ?P{custom}! With improvement in compiler technology, one may expect this difference inperformance to diminish..EX.EH.MB.RS.ip (a)Obtain the code for the C++ class @Stack@ without making use of theclass @LinearList@. I.e., start afresh and use an array @stack@to store the elements, an integer variable @top@ that points to thetop element in the stack (initialized to @- 1@), and an integervariable @MaxSize@ that gives the largest number of elements thestack can hold..ip (b)Write a program to measure the run time of an alternating sequence of@n@ stack add and delete operations. Measure the times neededby Programs ?p{stackclass}, ?p{custom}, and your code of part (a)..ip (c)What can you say about the merits/demerits of the different softwaredevelopment styles used?.RE.EHExtend the stack ADT by adding functions to:.RS.ip (a)Determine the size (i.e., number of elements) of the stack..ip (b)Input a stack..ip (c)Print a stack..RENow extend the class definition of a formula-based stack to includecode for these functions..EHExtend the stack ADT by adding functions to:.RS.ip (a)Split a stack into two. The first contains the bottom half elements and the second the remaining elements..ip (b)Combine two stacks into one by placing all elements of the second stackon top of those in the first. The relative order of elements from thesecond stack is unchanged..RENow extend the class definition of a formula-based stack to includecode for these functions..LP.oh "Linked Representation".NH 2LINKED REPRESENTATION.LP.spWhile the array representation of a stack considered in the previoussection is both elegant and efficient, it is wastefulof space when multiple stacks are to co-exist. The reasons are the same asthose cited in Chapter 2 for the inefficiency of the separate arraysfor separate listsrepresentation. An exception iswhen only two stacks are to co-exist. Now, space and time efficiency can bemaintainedby pegging the bottom of one stack at position 0and the bottom of the other at position @MaxSize - 1@. The two stacksgrow towards the middle of the array (see ?F{twostacks}). When more thantwo stacks are to be represented,the multiple lists in a single array representation may be adaptedto the case of multiple stacks. While this results in aspace efficient implementation,the worst case add time becomes\*(OH(@ArraySize@) rather than \(*H(1). The delete time remains \(*H(1)..KF.hl.PSh = .5i; w = .3i;X:[boxht = h; boxwid = wA: box shade 5B: box shade 5C: box shade 5D: box shade 5]boxwid = 5*w; box "@...@"; boxwid = wY:[E: box shade 30;F: box shade 30G: box shade 30H: box shade 30]y = .1arrow from X.D.t+(0,.4) to X.D.tarrow from Y.E.t+(0,.4) to Y.E.t"\fItop\fR1" at X.D.t+(0,.4+y)"\fItop\fR2" at Y.E.t+(0,.4+y)"[0]" at X.A.t+(0,.2)"@ArraySize - 1@" at Y.H.t+(0,.2)"STACK 1" at X.b-(0,.2)"STACK 2" at Y.b-(0,.2)arrow right .5i from X.D.earrow left .5i from Y.E.w.PE.hl\fB?F{twostacks}:\fR Two stacks in an array.KE.ppMultiple stacks can be represented efficiently using a chain for eachstack.This representation incurs a space penalty of one pointer field for eachstack element. However, each stack operation can be performed in\(*H(1) time.When using a chain to represent a stack, we must decide which endof the chain corresponds to the stack top. If we associate the rightend of the chain with the stack top, then stack additionsand deletions are implemented using thechain operations @Insert(n, x)@and @Delete(n,x)@ where @n@ is the number of nodes inthe chain. Each of these chain operations takes \(*H(@n@) time.On the other hand, if we associate the left end of the chain withthe stack top, then the chain operations to use are@Insert(0, x)@ and @Delete(1,x)@. Each of these takes \(*H(1)time. As a result of this, the left end of the chain represents thestack top. The resulting class definition of a linked stack
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -