1 Stacks Chapter 4. 2 Objectives You will be able to: Describe a stack as an ADT. Build a dynamic-array-based implementation of stacks. Build a linked-list.

Slides:



Advertisements
Similar presentations
Queues A waiting line that grows by adding elements to its end and shrinks by taking elements from its front Line at the grocery store Cars in traffic.
Advertisements

The unorganized person’s data structure
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.
Copyright © 2012 Pearson Education, Inc. Chapter 18: Stacks And Queues.
Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.
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
Exceptions OO Software Design and Construction Computer Science Dept Va Tech January 2002 ©2002 McQuain WD & Keller BJ 1 Exceptions exceptiona program.
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.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
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.
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 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks.
1 Lecture 24 Abstract Data Types (ADT) –I Overview  What is an Abstract Data type?  What is Stack ADT?  Stack ADT Specifications  Array Implementation.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
1 Chapter 6 Lists Plus. ADT Sorted List Operations Transformers n MakeEmpty n InsertItem n DeleteItem Observers n IsFull n LengthIs n RetrieveItem Iterators.
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.
Data Structures Chapter 2 Stacks Andreas Savva. 2 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one.
Object Oriented Data Structures
CS 1031 C++: Object-Oriented Programming Classes and Objects Template classes Operator Overloading Inheritance Polymorphism.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
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.
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.
Templates Zhen Jiang West Chester University
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.
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,
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.
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)
Stack. 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.
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.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
1 Linked Stack Chapter 4. 2 Linked Stack We can implement a stack as a linked list. Same operations. No fixed maximum size. Stack can grow indefinitely.
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.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
Introduction to Stacks Chapter 2. Objectives Introduce abstract data types. Discuss implementation types. – Static – Dynamic – Contiguous Introduce the.
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.
EASTERN MEDITERRANEAN UNIVERSITY Stacks EENG212 –Algorithms and Data Structures.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
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.
Data Structures & Algorithms
1 Linked Lists II Doubly Linked Lists Chapter 3. 2 Objectives You will be able to: Describe, implement, and use a Doubly Linked List of integers.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
11 Introduction to Object Oriented Programming (Continued) Cats.
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 Queues Chapter 4. 2 Objectives You will be able to Describe a queue as an ADT. Build a dynamic array based implementation of a queue ADT.
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
Click to edit Master text styles Stacks Data Structure.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
1 Data Structures CSCI 132, Spring 2016 Notes_ 5 Stacks.
Popping Items Off a Stack Using a Function Lesson xx
Stacks Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Popping Items Off a Stack Lesson xx
CSC 143 Stacks [Chapter 6].
COMPUTER 2430 Object Oriented Programming and Data Structures I
Stacks CS-240 Dick Steflik.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Abstract Data Types Stacks CSCI 240
Presentation transcript:

1 Stacks Chapter 4

2 Objectives You will be able to: Describe a stack as an ADT. Build a dynamic-array-based implementation of stacks. Build a linked-list implementation of stacks.

3 Stack A stack is a last-in-first-out (LIFO) data structure. Basic Operations: Add an item Referred to as pushing it onto the stack Remove an item Referred to as popping it from the stack

4 Stack as an ADT Definition: An ordered collection of data items. Can be accessed only at one end, the top Operations: Construct an empty stack Check if a stack is empty Push: Add an element to the top Pop:Remove the top element Top: Retrieve the top element

5 Example Consider a program to convert decimal numbers to binary Repeatedly Divide the decimal value by 2 Push the remainder onto a stack Continue until quotient is 0 Pop values off the stack and output

6 A Simple Stack Template Store stack elements in a dynamically allocated array. Member variable identifies top of stack. Throw an exception if client attempts to push an element when stack is full or pop an element when stack is empty.

7 Create Project Create a new empty C++ Console Application Project Simple_Stack_Demo Add stack.h Add stack_test.cpp Code is available at: _02_07_Stacks/ _02_07_Stacks/

stack.h #pragma once #include template class Stack { public:... private: T* data; // Dynamically allocated array int size; // Number of elements int top; // Index of element at top of stack // -1 when stack is empty };

stack.h #pragma once #include template class Stack { public: Stack(int capacity = 1000); ~Stack(); bool IsEmpty() const {return top == -1;}; bool IsFull() const {return top == size-1;}; // Add a value to the top of the stack. void Push(const T& value); // Remove and return value at top of stack. T Pop(); // Retrieve value at top of stack without removing it. T Top() const; // Display stack contents. void Display(std::ostream& out) const;

10 Constructor and Destructor template Stack ::Stack(int capacity): top(-1), size(capacity) { data = new T[capacity]; assert (data != 0); } template Stack ::~Stack() { delete[] data; }

11 Push() template void Stack ::Push(const T& value) { if (this->IsFull()) { throw "Stack overflow"; } data[++top] = value; }

12 Pop() template T Stack ::Pop() { if (this->IsEmpty()) { throw "Pop called for empty stack"; } return data[top--]; }

13 Top() template T Stack ::Top() const { if (this->IsEmpty()) { throw "Top of empty stack requested"; } return (data[top]); }

14 stack_test.cpp #include #include "Stack.h" #include using namespace std; const int STACK_CAPACITY = 10; int main() { Stack s(STACK_CAPACITY); assert (s.IsEmpty()); cout << "Newly created stack is empty\n"; printf ("Pushing 0 - %d \n", STACK_CAPACITY - 1); for (int i = 0; i < STACK_CAPACITY; ++i) { s.Push(i); } cout << "Initial stack:\n"; s.Display(cout);

15 stack_test.cpp assert(!s.IsEmpty()); cout << "Now the stack is not empty\n"; cout << "Adding one more element, which should cause overflow. " << endl; try { s.Push(1); cout << "ERROR\n"; // Should have thrown exception } catch (const char* msg) { cout << "Attempt to overfill stack threw exception as expected\n"; cout << "Message: " << msg << endl; } cout << "Stack should be unchanged\n" << endl; s.Display(cout);

16 stack_test.cpp cout << "Now poping elements off the stack\n"; while (!s.IsEmpty()) { int top = s.Top(); cout << "Stack top: " << top << endl; int next_item = s.Pop(); assert (next_item == top); } cout << "Stack is now empty\n"; cout << "Getting top of empty stack. This should fail\n"; try { int x = s.Top(); cout << "ERROR\n"; // Should have thrown exception } catch (const char* msg) { cout << "Attempt to get top of empty stack threw exception as expected\n"; cout << "Message: " << msg << endl; }

17 stack_test.cpp cout << "Doing one more pop. This should fail\n"; try { s.Pop(); cout << "ERROR\n"; // Should have thrown exception cin.get(); } catch (char* msg) { cout << "Attempt to pop empty stack threw exception as expected\n"; cout << "Message: " << msg << endl; }

18 stack_test.cpp cout << "Testing dynamic allocation\n"; Stack * s2 = new Stack (STACK_CAPACITY); assert(s2 != 0); cout << "Allocation was successful\n"; cout << "Testing delete\n"; delete(s2); s2 = 0; cout << "Delete was successful\n"; cout << "Test complete. Press Enter to exit." << endl; cin.get(); // Hold window open return 0; }

19 Program Running

20 Program Running

21 An Application: Decimal to Binary Conversion stack_demo.cpp /* This program uses a stack to convert the base-ten representation of a positive integer entered as input to base two, which is then output */ #include #include "Stack.h" using namespace std; int main() { int number; // the number to be converted int remainder; // remainder when number is divided by 2 Stack remainders; // stack of remainders cout << "This program displays the binary representation of integers\n"; cout << "that you specify. Enter 0 to end program\n\n";

22 stack_demo.cpp while (true) { cout << "Enter positive integer to convert: "; cin >> number; if (number <= 0) { break; } while (number != 0) { remainder = number % 2; remainders.Push(remainder); number /= 2; } cout << "Base-two representation: "; while (!remainders.IsEmpty() ) { remainder = remainders.Pop(); cout << remainder; } cout << endl << endl; }

23 stack_demo.cpp cin.get(); // Hold window open cin.get(); return 0; }

24 Program in Action

25 Allocation Failure Let’s see if we can force an allocation failure and see what happens. Stack remainders(INT_MAX); // stack of remainders

26 stack_test.cpp #include #include "Stack.h" #include using namespace std; int main() { try { Stack* s = new Stack (INT_MAX); assert(s != 0); cout << "Allocation was successful\n"; } catch (bad_alloc& ba) { cout << "Caught Bad Allocation exception\n"; cout << ba.what() << endl; } cout << "Test complete. Press enter to exit.\n"; cin.get(); // Hold window open return 0; }

27 Running on Windows Click here

28 Running on Windows

29 Running on Linux