Lec 7
Lec 7
Stacks
Linked-list Based
What is a stack?
§ It is an ordered group of homogeneous items.
§ Items are added to and removed from the top of the
stack
LIFO property: Last In, First Out
§ The last item added would be the first to be removed
Linked-list-based
Linked-list-based Stacks
template<class ItemType>
struct NodeType<ItemType> {
ItemType info;
NodeType<ItemType>* next;
};
Linked-list-based Stacks (cont’d)
template<class ItemType>
struct NodeType<ItemType>;
template<class ItemType>
class StackType {
public:
StackType();
~StackType();
void MakeEmpty();
bool IsEmpty() const;
bool IsFull() const;
void Push(ItemType);
void Pop(ItemType&);
private:
NodeType<ItemType>* topPtr;
};
Linked-list-based Stacks (cont’d)
template<class ItemType>
StackType<ItemType>::StackType()
{
topPtr = NULL; O(1)
}
template<class ItemType>
void StackType<ItemType>::MakeEmpty()
{
NodeType<ItemType>* tempPtr;
while(topPtr != NULL) {
tempPtr = topPtr;
topPtr = topPtr->next;
delete tempPtr; O(N)
}
}
Linked-list-based Stacks (cont’d)
template<class ItemType>
StackType<ItemType>::~StackType()
{
MakeEmpty(); O(N)
}
template<class ItemType>
bool StackType<ItemType>::IsEmpty() const
{
return(topPtr == NULL);
} O(1)
Linked-list-based Stacks (cont’d)
template<class ItemType>
bool StackType<ItemType>::IsFull() const
{
NodeType<ItemType>* location;
Need a
temporary
pointer !
Special case: popping the last
element on the stack
tempPtr
Function Pop
template <class ItemType>
void StackType<ItemType>::Pop(ItemType& item)
{
NodeType<ItemType>* tempPtr;
item = topPtr->info;
tempPtr = topPtr;
topPtr = topPtr->next; O(1)
delete tempPtr;
}
Comparing stack implementations
Big-O Comparison of Stack Operations
Operation Array Linked
Implementation Implementation
Constructor O(1) O(1)
MakeEmpty O(1) O(N)
IsFull O(1) O(1)
IsEmpty O(1) O(1)
Push O(1) O(1)
Pop O(1) O(1)
Destructor O(1) O(N)
Array-based vs Linked-list-based
Stack Implementations
§ Array-based implementation is simple but:
§ The size of the stack must be determined when a stack object is
declared.
§ Space is wasted if we use less elements.
§ We cannot "enqueue" more elements than the array can hold.
while (!Stack.IsEmpty()) { 3 1
Stack.Pop(item);
if (item==oldItem) 2 5
tempStack.Push(newItem); 1 3
else Stack
tempStack.Push(item);
}
while (!tempStack.IsEmpty()) {
tempStack.Pop(item);
Stack.Push(item); 3
}
oldItem = 2 5
}
newItem = 5 1
{
ItemType item;
StackType tempStack;