11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.

Slides:



Advertisements
Similar presentations
The unorganized person’s data structure
Advertisements

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.
COMPSCI 105 S Principles of Computer Science 13 Stacks.
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 ADT Stack Figure 6.1 Stack of cafeteria dishes A stack –Last-in, first-out (LIFO)
CMPT 225 Stacks-part2.
CMPT 225 Stacks.
Stacks CS-240 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed in reverse.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
© 2006 Pearson Addison-Wesley. All rights reserved7 B-1 Chapter 7 (continued) Stacks.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 ADT Stack Figure 6.1 Stack of cafeteria dishes A stack –Last-in, first-out (LIFO)
1 Stacks (Walls & Mirrors - Chapter 6). 2 Overview The ADT Stack Array Implementation of a Stack Linked-List Implementation of a Stack Application Domain:
Chapter 6 Stacks. © 2005 Pearson Addison-Wesley. All rights reserved6-2 The Abstract Data Type Specifications of an abstract data type for a particular.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Stacks CS-240 & CS-341 Dick Steflik. Stacks Last In, First Out operation - LIFO As items are added they are chronologically ordered, items are removed.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
© 2006 Pearson Addison-Wesley. All rights reserved7A-1 Chapter 7 Stacks (and a bit of generics for flavor)
Chapter 7 Stacks II CS Data Structures I COSC 2006
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.
What is a Stack? n Logical (or ADT) level: A stack is an ordered group of homogeneous items in which the removal and addition of items can take place only.
1 Stacks – Chapter 3 A stack is a data structure in which all insertions and deletions of entries are made at one end, called the top of the stack. Alternatively,
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
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.
Chapter 7 Stacks. © 2004 Pearson Addison-Wesley. All rights reserved 7-2 The Abstract Data Type: Developing an ADT During the Design of a Solution Specifications.
1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 7: Queues Data Abstraction & Problem Solving with C++
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 6: Stacks Data Abstraction & Problem Solving with C++
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Data Structures Stack Namiq Sultan 1. Data Structure Definition: Data structures is a study of different methods of organizing the data and possible operations.
Lecture 6: Stacks 1. 2 The Abstract Data Type Specifications of an abstract data type for a particular problem –Can emerge during the design of the problem’s.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
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.
Chapter 6 B Stacks. © 2004 Pearson Addison-Wesley. All rights reserved6 B-2 Comparing Implementations All of the three implementations are ultimately.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
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.
6/12/20161 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.
Stacks The Stack ADT stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) scheme. The last item placed.
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.
Abstract Data Types (ADTs)
Data Structures Using C++ 2E
CENG 213 Data Structures Stacks 5/15/2018 CENG 213.
CC 215 Data Structures Stack ADT
Abstract Data Types (ADTs)
Homework 4 questions???.
Stack.
Chapter 6 Stacks.
Stacks Data structure Elements added, removed from one end only
Jordi Cortadella and Jordi Petit Department of Computer Science
Abstract Data Types (ADTs)
Chapters 6 and 7 Stacks.
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
5.3 Implementing a Stack Chapter 5 – The Stack.
Presentation transcript:

11/07/141 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the data –Error conditions associated with operations

11/07/142 The Stack ADT The Stack ADT stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) scheme. The last item placed on the stack will be the first item removed. (similar to a stack of dishes) Stack of Dishes

11/07/143 ADT Stack Operations Create an empty stack Destroy a stack Determine whether a stack is empty Add a new item -- push Remove the item that was added most recently -- pop Retrieve the item that was added most recently pushpop Stack top

11/07/144 ADT Stack Operations(cont.) Stack() –creates a an empty stack ~Stack() –destroys a stack isEmpty():boolean –determines whether a stack is empty or not push(in newItem:StackItemType) –Adds newItem to the top of a stack pop() throw StackException topAndPop(out stackTop:StackItemType) –Removes the top of a stack (ie. removes the item that was added most recently getTop(out stackTop:StackItemType) –Retrieves the top of stack into stackTop

11/07/145 Implementations of the ADT Stack The ADT stack can be implemented using –An array –A linked list –The ADT list (linked list of the previous lecture) All three implementations use a StackException class to handle possible exceptions class StackException { public: StackException(const string& err) : error(err) {} string error; };

11/07/146 Implementations of the ADT Stack (cont.) 2 1 0

11/07/147 An Array-Based Implementation of the ADT Stack Private data fields –An array of items of type StackItemType –The index top Compiler-generated destructor, copy constructor, and assignment operator

11/07/148 An Array-Based Implementation –Header File #include "StackException.h" const int MAX_STACK = maximum-size-of-stack; template class Stack { public: Stack(); // default constructor; copy constructor and destructor are supplied by the compiler // stack operations: bool isEmpty() const; // Determines whether a stack is empty. void push(const T& newItem);// Adds an item to the top of a stack. void pop(); // Removes the top of a stack. void topAndPop(T& stackTop); void getTop(T& stackTop) const; // Retrieves top of stack. private: T items[MAX_STACK]; // array of stack items int top; // index to top of stack };

11/07/149 An Array-Based Implementation template Stack ::Stack(): top(-1) {} // default constructor template bool Stack ::isEmpty() const { return top < 0; }

11/07/1410 An Array-Based Implementation template void Stack ::push(const T& newItem) { if (top >= MAX_STACK-1) throw StackException("StackException: stack full on push"); else items[++top] = newItem; }

11/07/1411 An Array-Based Implementation – pop template void Stack ::pop() { if (isEmpty()) throw StackException("StackException: stack empty on pop"); else --top; // stack is not empty; pop top }

11/07/1412 An Array-Based Implementation – pop template void Stack ::topAndPop(T& stackTop) { if (isEmpty()) throw StackException("StackException: stack empty on pop"); else // stack is not empty; retrieve top stackTop = items[top--]; }

11/07/1413 An Array-Based Implementation – getTop template void Stack ::getTop(T& stackTop) const { if (isEmpty()) throw StackException("StackException: stack empty on getTop"); else stackTop = items[top]; }

11/07/1414 An Array-Based Implementation Disadvantages of the array based implementation is similar the disadvantages of arrays Furthermore, it forces all stack objects to have MAX_STACK elements We can fix this limitation by using a pointer instead of an array template class Stack { public: Stack(int size) : items(new T [size]) { };... // other parts not shown private: T* items; // pointer to the stack elements int top; // index to top of stack }; “Need to implement copy constructor, destructor and assignment operator in this case”

11/07/1415 A Pointer-Based Implementation of the ADT Stack A pointer-based implementation –Required when the stack needs to grow and shrink dynamically –Very similar to linked lists top is a reference to the head of a linked list of items A copy constructor, assignment operator, and destructor must be supplied

11/07/1416 A Pointer-Based Implementation – Header File #include "StackException.h" template class Stack{ public: Stack(); // default constructor Stack(const Stack& rhs); // copy constructor ~Stack(); // destructor Stack& operator=(const Stack& rhs); // assignment operator bool isEmpty() const; void push(const T& newItem); void pop(); void topAndPop(T& stackTop); void getTop(T& stackTop) const;

11/07/1417 A Pointer-Based Implementation – Header File private: // Note that we are defining StackNode as a nested private class to make it usable only by our Stack class. template struct StackNode { // a node on the stack StackNode(const S& data = S(), StackNode * ptr = NULL) { data = item; next = ptr; } S item; // a data item on the stack StackNode *next; // pointer to next node }; StackNode *topPtr; // pointer to the first node in the stack };

11/07/1418 A Pointer-Based Implementation – constructor and isEmpty template Stack ::Stack() : topPtr(NULL) {} // default constructor template bool Stack ::isEmpty() const { return topPtr == NULL; }

11/07/1419 A Pointer-Based Implementation – push template void Stack ::push(const T& newItem) { // create a new node StackNode *newPtr = new StackNode(newItem, topPtr); topPtr = newPtr; // update the stack top }

11/07/1420 A Pointer-Based Implementation – pop template void Stack ::pop() { if (isEmpty()) throw StackException("StackException: stack empty on pop"); else { StackNode *tmp = topPtr; topPtr = topPtr->next; // update the stack top delete tmp; }

11/07/1421 A Pointer-Based Implementation – topAndPop template void Stack ::topAndPop(T& stackTop) { if (isEmpty()) throw StackException("StackException: stack empty on topAndPop"); else { stackTop = topPtr->item; StackNode *tmp = topPtr; topPtr = topPtr->next; // update the stack top delete tmp; }

11/07/1422 A Pointer-Based Implementation – getTop template void Stack ::getTop(T& stackTop) const { if (isEmpty()) throw StackException("StackException: stack empty on getTop"); else stackTop = topPtr->item; }

11/07/1423 A Pointer-Based Implementation – destructor template Stack ::~Stack() { // pop until stack is empty while (!isEmpty()) pop(); }

11/07/1424 A Pointer-Based Implementation – assignment template Stack & Stack ::operator=(const Stack& rhs) { if (this != &rhs) { while (!isEmpty()) // make the current stack empty pop(); if (rhs.topPtr) { topPtr = new StackNode (rhs.topPtr->item); StackNode * q = rhs.topPtr->next; StackNode * p = topPtr; while (q) { p->next = new StackNode (q->item); p = p->next; q = q->next; } return *this; }

11/07/1425 A Pointer-Based Implementation – copy constructor template Stack ::Stack(const Stack& rhs) { topPtr = NULL; // think about why we need this! *this = rhs; // reuse assignment operator }

11/07/1426 Testing the Stack Class int main() { Stack s; for (int i = 0; i < 10; i++) s.push(i); Stack s2 = s; // test copy constructor (also tests assignment) std::cout << "Printing s:" << std::endl; while (!s.isEmpty()) { int value; s.topAndPop(value); std::cout << value << std::endl; }

11/07/1427 Testing the Stack Class std::cout << "Printing s2:" << std::endl; while (!s2.isEmpty()) { int value; s2.topAndPop(value); std::cout << value << std::endl; } return 0; }

11/07/1428 An Implementation That Uses the ADT List #include "StackException.h" #include "List.h" template class Stack{ public: bool isEmpty() const; void push(const T& newItem); void pop(); void topAndPop(T& stackTop); void getTop(T& stackTop) const; private: List list; }

11/07/1429 An Implementation That Uses the ADT List No need to implement constructor, copy constructor, destructor, and assignment operator –The member list 's functions will be called when needed isEmpty(): return list.isEmpty() push(x): list.push_front(x) pop(): list.remove(list.first()->element) topAndPop(&x) and getTop(&x) are similar StackException should be thrown when needed Implement this class as an exercise

11/07/1430 Comparing Implementations Array based: –Fixed size (cannot grow and shrink dynamically) Using a single pointer: –May need to reallocate, copy, and destroy memory when the currently allocated size is exceeded –But push and pop operations can be very fast Using a customized linked-list: –The size can match perfectly to the contained data –Push and pop can be a bit slower than above Using the previously defined linked-list: –Reuses existing implementation –Reduces the coding effort but may be a bit less efficient

11/07/1431 Application: Algebraic Expressions To evaluate an infix expression –Convert the infix expression to postfix form (see infixToPostfix.cpp on the webpage) –Evaluate the postfix expression (see evalPostFix.cpp on the webpage) Infix ExpressionPostfix Expression * * + 5 * * * ( ) * 4 -

11/07/1432 Evaluating Postfix Expressions When an operand is entered, the calculator –Pushes it onto a stack When an operator is entered, the calculator –Applies it to the top two operands of the stack –Pops the operands from the stack –Pushes the result of the operation on the stack

11/07/1433 Evaluating Postfix Expressions – *

11/07/1434 Converting Infix Expressions to Postfix Expressions An infix expression can be evaluated by first being converted into an equivalent postfix expression Facts about converting from infix to postfix –Operands always stay in the same order with respect to one another –An operator will move only “to the right” with respect to the operands –All parentheses are removed

11/07/1435 Converting Infix Expr. to Postfix Expr. -- Algorithm for (each character ch in the infix expression) { switch (ch) { case operand: // append operand to end of postfixExpr postfixExpr=postfixExpr+ch; break; case ‘(‘:// save ‘(‘ on stack aStack.push(ch); break; case ‘)’:// pop stack until matching ‘(‘, and remove ‘(‘ while (top of stack is not ‘(‘) { postfixExpr=postfixExpr+(top of stack); aStack.pop(); } aStack.pop(); break;

11/07/1436 Converting Infix Expr. to Postfix Expr. -- Algorithm case operator:// process stack operators of greater precedence while (!aStack.isEmpty() and top of stack is not ‘(‘ and precedence(ch) <= precedence(top of stack) ) { postfixExpr=postfixExpr+(top of stack); aStack(pop); } aStack.push(); break;// save new operator } } // end of switch and for // append the operators in the stack to postfixExpr while (!isStack.isEmpty()) { postfixExpr=postfixExpr+(top of stack); aStack(pop); }

11/07/1437 Converting Infix Expressions to Postfix Expressions a - (b + c * d)/ e  a b c d * + e / -

11/07/1438 The Relationship Between Stacks and Recursion A strong relationship exists between recursion and stacks Typically, stacks are used by compilers to implement recursive methods (in general, all function calls are implemented by using a stack) During execution, each recursive call generates an activation record that is pushed onto a stack That's why we can get stack overflow error if a function makes makes too many recursive calls Stacks can be used to implement a non-recursive version of a recursive algorithm

11/07/1439 Example: Reversing a string void printReverse(const char* str) { if (*str) { printReverse(str + 1) cout << *str << endl; }

11/07/1440 Example: Reversing a string void printReverseStack(const char* str) { Stack s; for (int i = 0; str[i] != 0; ++i) s.push(str[i]); while(!s.isEmpty()) { char c; s.topAndPop(c); cout << c; }

11/07/1441 Other Applications Checking for matching parenthesis Undo/redo functionality in many software programs Scheduling algorithms Compilers Expression processing Search problems that require backtracking (such as Mazes)...

11/07/1442 Stacks -- Summary ADT stack operations have a last-in, first-out (LIFO) behavior There are different stack implementations –Array-Based, Pointer-Based, Linked-list based Many stack applications –expression processing –language recognition –search problem (maze problems) A strong relationship exists between recursion and stacks –Any recursive program can be rewritten as a non-recursive program using stacks.