Stacked Deque Gordon College Stacked Decks - get it?

Slides:



Advertisements
Similar presentations
Data Structures Through C
Advertisements

Chapter 6 Queues and Deques.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
Data Structure (Part I) Stacks and Queues. Introduction to Stack An stack is a ordered list in which insertion and deletions are made at one end. –The.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
1 Queues CPS212 Gordon College. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank, food.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
1 Queues and Priority Queues Chapter 8. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank,
Chapter 16 Stacks and Queues Saurav Karmakar Spring 2007.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
1 4. Stacks Introduction Consider the 4 problems on pp (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
Stack Applications.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
Containers Overview and Class Vector
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stacks CHAPTER 7 MAY 21, 2015 Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Exam Review 5/28/15. Software Development (Review)  Make it work…then make it pretty can result in dangerous code  Better to take a unified, consistent.
1 4. Stacks Introduction Consider the 4 problems on pp (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses.
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Lecture 7 : Intro. to STL (Standard Template Library)
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part 2a. Simple Containers: The Stack.
Data Structure By Amee Trivedi.
Stacks Stacks.
Dr. Bernard Chen Ph.D. University of Central Arkansas
Homework 4 questions???.
Stacks Chapter 7 introduces the stack data type.
Objectives In this lesson, you will learn to: Define stacks
Data Structures Interview / VIVA Questions and Answers
Cinda Heeren / Geoffrey Tien
Stacks Chapter 4.
CMSC 341 Lecture 5 Stacks, Queues
Array Lists Chapter 6 Section 6.1 to 6.3
Lecture 8 : Intro. to STL (Standard Template Library)
Jordi Cortadella and Jordi Petit Department of Computer Science
LINEAR DATA STRUCTURES
Presentation transcript:

Stacked Deque Gordon College Stacked Decks - get it? Adapted from Nyhoff, ADTs, Data Structures and Problem Solving with C++ Stacked Decks - get it?

Introduction to Stacks A stack is a last-in-first-out (LIFO) data structure Adding an item Referred to as pushing it onto the stack Removing an item Referred to as popping it from the stack Cards – some programming problems are just best solved using stacks…

A Stack Definition: Operations: An ordered collection of data items Can be accessed at only one end (the top) Operations: construct a stack (usually empty) check if it is empty Push: add an element to the top Top: retrieve the top element Pop: remove the top element

Stack STL specifics value_type size_type (type constant within class) stack() (default constructor) stack(const stack&) (copy constructor) stack& operator=(const stack&) (assignment operator) bool empty() const size_type size() const value_type& top() const value_type& top() const void push(const value_type&) void pop() bool operator==(const stack&, const stack&) These are available… bool operator<(const stack&, const stack&) (Uncertain how these are suppose to work….lexigraphical Using the lexiographical compare function from <algorithm>

Example Program Consider a program to do base conversion of a number (from base ten to base two) Program to accomplish this Demonstrates push, pop, and top Have studetns come up with this one.

#include <stack> #include <iostream> using namespace std; void convert(int arg) { stack<int> binary; while(arg>0) binary.push(arg%2); arg /= 2; } cout << endl; while(!binary.empty()) cout << binary.top(); binary.pop(); int main() convert(101); return 0;

Stack Programming Application Example Use a stack ADT in a program that reads a string, one character at a time and determines whether the string contains balanced parentheses (for each left parentheses - there should be a right)

Deque double-ended queue (pronounced deck) - elements are ordered following a strict linear sequence. Properties Individual elements can be accessed by their position index. Iteration over the elements can be performed in any order. Elements can be efficiently added and removed from any of its ends (either the beginning or the end of the sequence). double-ended stack “deck” Like the vector in these ways - however not guaranteed to have all its elements in contiguous storage locations

Deque For frequent insertion or removals of elements at positions other than the beginning or the end, deques perform worse and have less consistent iterators and references than lists. Like a vector: a sequence that supports random access to elements constant time insertion and removal of elements at the end of the sequence linear time insertion and removal of elements in the middle. Not like a vector: constant time insertion and removal of elements at the beginning of the sequence nothing like capacity() and reserve() void resize ( size_type sz, T c = T() ); [[Change size]] Resizes the container to contain sz elements. If sz is smaller than the current container size, the content is reduced to its first sz elements, the rest being dropped. If sz is greater than the current container size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements. Notice that this function changes the actual content of the container by inserting or erasing elements from it. Not like reserve -

STL Deque Element access: operator[] Access element at Access element front Access first element back Access last element Modifiers: assign Assign container content void assign ( InputIterator first, InputIterator last ); void assign ( size_type n, const T& u ); push_back Add element at the end push_front Insert element at begin pop_back Delete last element pop_front Delete first element insert Insert elements (iterator position) erase Erase elements swap Swap content clear Clear content Iterators: begin Return iterator to beginning end Return iterator to end rbegin Return reverse iterator to reverse beginning rend Return reverse iterator to reverse end Capacity: size Return size max_size Return maximum size resize Change size empty is empty? deque<int> first; // empty deque of ints Assign (replace current values with these) deque<int> second (4,100); // four ints with value 100 resize - reduced or expanded (see previous slide) deque<int> third (second.begin(),second.end()); // iterating through second [] - access based on position (index position) deque<int> fourth (third); // a copy of third at - same as [] but throws error if out of range // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

STL Deque Constructors deque<int> first; deque<int> second (4,100); deque<int> third (second.begin(),second.end()); deque<int> fourth (third); int myints[] = {16,2,77,29}; deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) ); deque<int> first; // empty deque of ints deque<int> second (4,100); // four ints with value 100 deque<int> third (second.begin(),second.end()); // iterating through second deque<int> fourth (third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

STL Deque Comparable to vector methods: void clear ( ); iterator erase ( iterator position ); iterator erase ( iterator first, iterator last ); reference front ( ); iterator insert ( iterator position, const T& x ); void insert ( iterator position, size_type n, const T& x ); void insert ( iterator position, InputIterator first, InputIterator last ); void pop_back ( ); void pop_front ( ); void push_back ( const T& x ); void push_front ( const T& x ); void swap ( deque<T,Allocator>& dqe );

STL Deque Access methods: const_reference at ( size_type n ) const; for (i=0; i<mydeque.size(); i++) mydeque.at(i)=i; cout << "mydeque contains:"; cout << " " << mydeque.at(i); Reference is return - access to element is obtained - to either read or write within slot

STL Deque Implementation Design criteria: Elements accessed by position Elements efficiently added/removed from either end Linear time add/removed from middle No guarantee to contiguous elements What sort of designs would work? What is the better design and why?

Deque Implementation two common ways to implement: a modified dynamic array an array of arrays can grow from both ends all the properties of a dynamic array: such as constant time random access good locality of reference inefficient insertion/removal in the middle constant time insertion/removal at both ends, instead of just one end. Sgi says linked-list. (not using a linked list - Why? Can not have direct access to elements.) MUST CONSIDER: Supports amortized constant time random access (like a vector) Allows amortized constant time insertions at the beginning and end

Deque Implementation Common implementations for dynamic array: Using a circular buffer, and only resizing when the buffer becomes completely full. (back) OUT BACK OUT FRONT (front) IN BACK IN FRONT Resizing is costly

Deque Implementation Common implementations for dynamic array: Allocating deque contents from the center of the underlying array, and resizing the underlying array when either end is reached. This approach may require more frequent resizings and waste more space, particularly when elements are only inserted at one end. Reference is return - access to element is obtained - to either read or write within slot Back Front

Deque Implementation A dynamic array of fixed arrays (blocks) Deque class keeps all this information and provides a uniform access to the elements. block size is fixed and the array of blocks is dynamic - Deque is the middle ground between list and vector…fairly efficient insert/removal in the middle and not a pointer needed for every element.

STL Stack Implementation Design criteria: Efficient access of top element Elements efficiently added/removed from one end What sort of design would work? What is the better design and why?

Stack implementation possibilities Selecting a Storage Structure for a Stack Model with an array Let position 0 be top of stack Problem … consider pushing and popping Requires much shifting Position 0 is the TOP… Push requires a shift down Pop requires a shift up NOT EFFICIENT

Selecting Storage Structure A better approach is to let position 0 be the bottom of the stack Thus our design will include An array to hold the stack elements An integer to indicate the top of the stack Con - fixed array

Implementing Operations Constructor (static array) Compiler will handle allocation of memory Empty Check if value of myTop == -1 Push (if myArray not full) Increment myTop by 1 Store value in myArray[myTop] Top If stack not empty, return myArray[myTop] Pop If array not empty, decrement myTop Implement this stack class on board.

Dynamic Array to Store Stack Elements Issues regarding static arrays for stacks: Can run out of space if stack set too small Can waste space if stack set too large As before, we demonstrate a dynamic array implementation to solve the problems What additional data members required? Pointer, size, capacity, (methods - destructor, copy constructor, assignment) Stack_ptr - pointer to dynamic stack Capacity - capacity of stack

Dynamic Array to Store Stack Elements Constructor stack A(5) must: Check that specified numElements > 0 Set capacity to numElements Allocate an array pointed to by myArray with capacity = myCapacity Set myTop to -1 if allocation goes OK numElement is the parameter for the constuctor What additional methods are required for this dynamic array approach?

Dynamic Array to Store Stack Elements Class Destructor needed Avoids memory leak Deallocates array allocated by constructor

Dynamic Array to Store Stack Elements Copy Constructor needed for Initializations Passing value parameter Returning a function value Creating a temporary storage value Provides for deep copy

Dynamic Array to Store Stack Elements Assignment operator Again, deep copy needed copies member-by-member, not just address

Further Considerations What if dynamic array initially allocated for stack is too small? Terminate execution? Replace with larger array! Creating a larger array Allocate larger array Use loop to copy elements into new array Delete old array Point myArray variable at this new array WE’VE SEEN THIS BEFORE! Stack built on top of Vector (dynamic array)

Further Considerations Another weakness – in the previous scenario the type must be set with typedef mechanism This means we can only have one type of stack in a program Would require completely different stack declarations and implementations Solution: Class Template

Linked Stacks built on top of lists Another alternative to allowing stacks to grow as needed Linked list stack needs only one data member Pointer myTop Nodes allocated (but not directly part of stack class)

Implementing Linked Stack Operations Constructor Simply assign null pointer to myTop Empty Check for myTop == null Push Insertion at beginning of list Top Return data to which myTop points

Implementing Linked Stack Operations Pop Delete first node in the linked list ptr = myTop; myTop = myTop->next; delete ptr; Output Traverse the list for (ptr = myTop; ptr != 0; ptr = ptr->next) out << ptr->data << endl;

Implementing Linked Stack Operations Destructor Must traverse list and deallocate nodes Note need to keep track of ptr->next before calling delete ptr; Copy Constructor Traverse linked list, copying each into new node Attach new node to copy

Implementing Linked Stack Operations Assignment operator Similar to copy constructor Must first rule out self assignment Must destroy list in stack being assigned a new value

STL Stack Implementation implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container The underlying structure of the stack the standard container class templates vector, deque or list can be used. By default - deque is used. What are the pro and cons for each of these underlining implementations? Vector Pro - dynamic, only adding and removing from end Con - must add as you go - which means there will be a periodic price to pay Deque Pro - when adding over the size - then it is localized to a couple of block (not all the copying necessary) Con - only using one of deque (wasted space) List Pro - constant time payment when adding one over Con - overhead of the link addresses template < class T, class Container = deque<T> > class stack; stack<int, vector<int> > binary; (deque is used) stack<int> binary;

STL Stack Implementation Constructors for Stack deque<int> mydeque (3,100); // deque with 3 elements vector<int> myvector (2,200); // vector with 2 elements stack<int> first; // empty stack stack<int> second (mydeque); // stack initialized to copy of deque stack<int,vector<int> > third; // empty stack using vector stack<int,vector<int> > fourth (myvector);

Application of Stacks Consider events when a function begins execution Activation record (or stack frame) is created Stores the current environment for that function. Contents:

Run-time Stack (call stack) Functions may call other functions interrupt their own execution Must store the activation records to be recovered system then reset when first function resumes execution This algorithm must have LIFO behavior Structure used is the run-time stack

Use of Run-time Stack When a function is called … Copy of activation record pushed onto run-time stack Arguments copied into parameter spaces Control transferred to starting address of body of function

Use of Run-time Stack When function terminates Run-time stack popped Removes activation record of terminated function exposes activation record of previously executing function Activation record used to restore environment of interrupted function Interrupted function resumes execution

Call Stack for Motorola 68000 processor int CallingFunction(int x) { int y; CalledFunction(1,2); return (5); } void CalledFunction(int param1, int param2) { int local1, local2; local1 = param2; }

Application of Stacks Consider the arithmetic statement in the assignment statement: x = a * b + c Compiler must generate machine instructions LOAD a MULT b ADD c STORE x Note: this is "infix" notation The operators are between the operands Stopped 2/15/06

RPN or Postfix Notation Most compilers convert an expression in infix notation to postfix the operators are written after the operands So a * b + c becomes a b * c + Advantage: expressions can be written without parentheses Conversion from infix to postfix: Rule 1: Scan the infix expression from left to right. Immediately record an operand as soon as you identify it in the expression Rule 2: Record an operator as soon as you identify its operands RPN - reverse polish notation Infix Postfix (a+b)*c ab+c* (a*b+c)/d+e ab*c+d/e+

Postfix and Prefix Examples INFIX RPN (POSTFIX) PREFIX A + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D A B + + A B A B * C + + * A B C A B C + * * A + B C -A-B-C D A B C D--- A B-C-D- ---A B C D Prefix : Operators come before the operands RPN – reverse polish notation

Evaluating RPN Expressions "By hand" (Underlining technique): 1. Scan the expression from left to right to find an operator. 2. Locate ("underline") the last two preceding operands and combine them using this operator. 3. Repeat until the end of the expression is reached. Example: 2 3 4 + 5 6 - - * ® 2 3 4 + 5 6 - - * ® 2 7 5 6 - - * ® 2 7 -1 - * ® 2 7 -1 - * ® 2 8 * ® 2 8 * ® 16

Evaluating RPN Expressions By using a stack algorithm Initialize an empty stack Repeat the following until the end of the expression is encountered Get the next token (const, var, operator) in the expression Operand – push onto stack Operator – do the following Pop 2 values from stack Apply operator to the two values Push resulting value back onto stack When end of expression encountered, value of expression is the (only) number left in stack Note: if only 1 value on stack, this is an invalid RPN expression

Evaluation of Postfix Note the changing status of the stack

Converting Infix to RPN By hand: Represent infix expression as an expression tree: A * B + C A * (B + C) ((A + B) * C) / (D - E) * A + C C A B D E * + / - * A B + B C PLACE HIGHEST PRECEDENCE OPERATION AT LEAVES LRP - postorder LPR - inorder traversal PLR - preorder D x y x D y

Traverse the tree in Left-Right-Parent order (postorder) to get RPN: C A B D E * + / - Traverse the tree in Left-Right-Parent order (postorder) to get RPN: A B + C * D E - / Traverse tree in Parent-Left-Right order (preorder) to get prefix: C A B D E * + / - - D E / * + A B C C A B D E * + / - Traverse tree in Left-Parent-Right order (inorder) to get infix: — must insert ()'s LRP - postorder LPR - inorder traversal PLR - preorder ( ) / ( * C) (A + B) (D - E)

Another RPN Conversion Method By hand: "Fully parenthesize-move-erase" method: 1. Fully parenthesize the expression. 2. Replace each right parenthesis by the corresponding operator. 3. Erase all left parentheses. Examples: ((A * B) + C) A * B + C  (A * (B + C) ) A * (B + C)   ((A B * C +  A B * C +  (A (B C + *  A B C + *

Stack Algorithm convert from infix to postfix Initialize an empty stack of operators While no error && !end of expression Get next input "token" from infix expression If token is … "(" : push onto stack ")" : pop and display stack elements until "(" occurs, do not display it const, var, arith operator, left or right paren

Note: Left parenthesis in stack has lower priority than operators Stack Algorithm Note: Left parenthesis in stack has lower priority than operators operator if operator has higher priority than top of stack push token onto stack else pop and display top of stack repeat comparison of token with top of stack operand display it When end of infix reached, pop and display stack items until empty