Date post: | 18-Dec-2015 |
Category: |
Documents |
Upload: | marjory-reynolds |
View: | 232 times |
Download: | 7 times |
Stacks and Queues
• Dynamic 1-dimensional data structures– Insertion & deletion of elements (push & pop)– Take place only in either side of list
Stacks and Queues
• Q: Can we just use a linked-list with restrictions on insertions and deletions?
• A: That is a stack (or queue)
Stacks and Queues
• Usually – not always,– You start with an empty stack (or queue)– Insertion/deletion is incremental.– By the end of your program, they become empty
again because you have all the items processed.
Implementation
• By a linked list– void push( const ItemType& new_item );• Place the new_item at the “end” of current list• “end” – top in stacks, back in queues
– void pop();• Delete the top item (stack) or the front item (queue)• Destruct the item
– Then adjust the pointers of items and # of items accordingly
Implementation
• By a linked list– ItemType& top();• Only in stack, returns the top item
– ItemType& front();• Only in queue, returns the front item
Stack vs. Queue
• When do you use what?– Depends on the particular order of items to
process.– E.g., Depth-first-search vs. Breadth-first-search
Inheritance
• Why?– To reduce code redundancy– By sharing the same functions/variables among a
group of classes.• Sharing is directed, so inherited• From base-class to derived-class
– Polymorphism
Inheritance
• A “BaseballPlayer” is a “Person”• An “Employee” is a “Person”• A “Supervisor” is an “Employee”• A “Supervisor” is a “Person”
Inheritance
• A “BaseballPlayer” is a “Person”• An “Employee” is a “Person”• A “Supervisor” is an “Employee”• A “Supervisor” is a “Person”
Base-class
Derived-class
Inheritance
• A “BaseballPlayer” is a “Person”• An “Employee” is a “Person”• A “Supervisor” is an “Employee”• A “Supervisor” is a “Person”
Base-class
Derived-class
InheritanceBase-class
Derived-class
• A base-class defines functions/variables to share with its derived classes– Person.age()– Person.gender()
Inheritance
• A derived-class defines its own specific functions/variables– BaseballPlayer.team()– Employee.company()– Supervisor.subordinates()
• It can also modify inherited functions, if needed.
Base-class
Derived-class
Inheritance of Members
• All public members are inherited.– Int get_age();– Int m_age;– They can be used in derived classes.– Not constructor, destructor, assignment operator..
Virtual Function
• Overriding functions:– Multiple definitions with the same signature– We need to choose a specific one to run