






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







A stack is a LIFO (last-in-first-out) linear data structure.
Definition 1. A stack, S, of item type T is formally defined as a sequence of items of type T on which the following operations are defined:
Environments with heavy reliance on stacks may provide additional op- erations. Some of these are:
a. debug: display the contents of the stack.
b. size: returns the number of elements on the stack.
c. top: determines the item at the top of the stack.
d. swap: two top-most items are exchanged.
e. rotate: the three topmost items exchange places in a rotary fashion. Two variants of this operation are possible, most often called left and right rotate.
f. dup: the top item is popped and pushed again twice.
2 A Singly-linked-list-based Stack ADT
Here we consider a singly-linked-list-based implementation of the stack ADT. As is the case with any abstract data type, a variety of implementations are possible: one with iterators is possible, one with a doubly-linked list without iterators, just to name a few. The choice of which implementation is best de- pends on the particular application for which the ADT is been implemented. We leave the strategy for implementing a doubly-linked-list-based stack with an iterator class for classroom discussion. Pay close attention to the syn- tax when a templatized class grants friendship to another templatized class. Also, observe the forward declaration of the friend class before the class that grants the friendship.
template
/** destructor - returns the stack memory to the system; */ ~Stack
/** Determine whether the stack is empty. @return this function returns true if the stack is empty; otherwise, it returns false if the stack contains at least one node. */ bool isEmpty() const;
/** Inserts an item into the stack. @param item the value to be inserted. */ void push(T item);
/** Returns the item at the top of a non-empty stack or generates an exception if the stack is empty. @return item at the top of the stack. */ const T& top() const throw (StackException);
Delete an item from the top of the stack. Generates an exception if the stack is empty. @return item at the top. */ T pop() throw (StackException);
returns the size of the stack. @return the size of the stack / long size() const; private: template
/* nested Node class definition / template
template
template
template
template
template
while (!nums.isEmpty()) { cout<<nums.top()<<" is at the top of the stack."<<endl; x = nums.pop(); cout<<x<<" has been removed from the front."<<endl; } } catch(StackException e) { cerr<<e.what(); } cout<<endl; return 0; }
Practice Exercise (not-to-be turned in for grading):