CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in 2006. Office.

Slides:



Advertisements
Similar presentations
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Advertisements

Stacks Chapter 11.
Prefix, Postfix, Infix Notation
Joseph Lindo Abstract Data Types Sir Joseph Lindo University of the Cordilleras.
Lecture 5 Stack Sandy Ardianto & Erick Pranata © Sekolah Tinggi Teknik Surabaya 1.
COMPSCI 105 S Principles of Computer Science 13 Stacks.
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.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Lecture 12 – ADTs and Stacks.  Modularity  Divide the program into smaller parts  Advantages  Keeps the complexity managable  Isolates errors (parts.
Stacks.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
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.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
CHAPTER 6 Stacks. 2 A stack is a linear collection whose elements are added and removed from one end The last element to be put on the stack is the first.
Stacks, Queues, and Deques
Stacks, Queues, and Deques. A stack is a last in, first out (LIFO) data structure –Items are removed from a stack in the reverse order from the way they.
Stacks, Queues, and Deques
Objectives of these slides:
Chapter 7 Stack. Overview ● The stack data structure uses an underlying linear storage organization.  The stack is one of the most ubiquitous data structures.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
Topic 3 The Stack ADT.
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.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures and Algorithms
Chapter 4 Stacks Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving. Its called.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
 STACK STACK  BASIC STACK OPERATIONS BASIC STACK OPERATIONS  PUSH ALGORITHM PUSH ALGORITHM  POP ALGORITHM POP ALGORITHM  EVALUATING A POSTFIX EXPRESSION.
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.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
CSE 373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks; Eclipse.
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
COMPSCI 105 SS 2015 Principles of Computer Science 09 ADT & Stacks.
Stacks An Abstract Data Type. Restricted Access Unlike arrays, stacks only allow the top most item to be accessed at any time The interface of a stack.
CHP-3 STACKS.
Prefix, Postfix, Infix Notation. Infix Notation  To add A, B, we write A+B  To multiply A, B, we write A*B  The operators ('+' and '*') go in between.
Stacks Chapter 5 © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java, 4e Frank Carrano.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Click to edit Master text styles Stacks Data Structure.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
Stacks Chapter 3 Objectives Upon completion you will be able to
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
Lecture - 6(Stacks) On Data structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Lecture Outline What is a Stack? Array implementation of stacks Operations.
G.PULLAIAH COLLEGE OF ENGINEERING AND TECHNOLOGY
Revised based on textbook author’s notes.
MEMORY REPRESENTATION OF STACKS
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Cinda Heeren / Geoffrey Tien
Stacks.
Copyright ©2012 by Pearson Education, Inc. All rights reserved
STACK CHAPTER 03 Developed By :- Misha Ann Alexander Data Structures.
Visit for more Learning Resources
Stacks, Queues, and Deques
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Chapter 7 Stack.
More About Stacks: Stack Applications
Stacks, Queues, and Deques
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks.
Stacks, Queues, and Deques
More About Stacks: Stack Applications
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
© 2016 Pearson Education, Ltd. All rights reserved.
Presentation transcript:

CSC 231 Stacks 1 Devon M. Simmonds University of North Carolina, Wilmington TIME: Tuesday/Thursday 11:11:50am in 1012 & Thursday 3:30-5:10pm in Office hours: TR 1-2pm or by appointment. Office location: CI

CSC 231 Objectives 2 Describe the stack ADT Understand pre and post conditions for stack operations. Apply the stack ADT to real world applications. Explain how the Python virtual machine uses a stack to support function and method calls

CSC 231 3

CSC 231 Lists A list is an ordered collection of zero or more references to Python data objects. Lists are written as comma-delimited values enclosed in square brackets. The empty list is simply [ ]. 4

CSC 231 Creating Lists 5 list1 = list() # Create an empty list list2 = list([2, 3, 4]) # Create a list with elements 2, 3, 4 list3 = list(["red", "green", "blue"]) # Create a list with strings list4 = list(range(3, 6)) # Create a list with elements 3, 4, 5 list5 = list("abcd") # Create a list with characters a, b, c list1 = [] # Same as list() list2 = [2, 3, 4] # Same as list([2, 3, 4]) list3 = ["red", "green"] # Same as list(["red", "green"]) Creating list using the list class For convenience, you may create a list using the following syntax:

CSC 231 list Methods 6

CSC 231 Typical Operations on Lists Finding length of list Finding the smallest value Finding the largest value Summing the elements in the list Slicing a list Sorting a list Testing membership List comprehension Splitting a string into a list 7

CSC 231 … 8

CSC 231 Abstract Data Types (ADTs) An ADT is the specification of: ▫A set of objects (data) and ▫A set of operations performed on the objects ADT is specified without regard to: ▫Programming language ▫Implementation nuances 9

CSC 231 Stacks A stack is a linear list in which items are added and removed from one end of the list called its top. The Stack ADT (LIFO) ▫Stack S = {s 1 s 2 s 3 … s N } ▫Operations:  push(item) - adds a new item to the stack.  pop():item - removes and return item at the top of the stack.  peek ():item- returns item at top of stack, stack unchanged.  Peek is sometine called top  isEmpty() – returns True when the stack is empty.  size() - returns the number of items on the stack. 10

CSC 231 Overview of Stacks Stack: LIFO structure in which access is completely restricted to just one end, called the top ▫Basic operations: push and pop from Fundamentals of Python: From First Programs Through Data Structures 11

CSC 231 List/Array implementation of stacks A stack type is not built into Python To implement a stack, items are inserted and removed at the same end (called the top) Efficient list implementation requires that the top of the stack be towards the center of the array, not fixed at one end To use a list to implement a stack, you need both the array itself and an integer The integer tells you either: ▫Which location is currently the top of the stack, or ▫How many elements are in the stack 12

CSC 231 Pushing and popping If the bottom of the stack is at location 0, then an empty stack is represented by top = -1 or count = 0 To add (push) an element, either: ▫Increment top and store the element in stk[top]], or ▫Store the element in stk[count]] and increment count To remove (pop) an element, either: ▫Get the element from stk[top]] and decrement top, or ▫Decrement count and get the element in stk[count]] 13 top = 3 or count = stk:

CSC 231 After popping When you pop an element, do you just leave the “deleted” element sitting in the array? The surprising answer is, “it depends” ▫If this is an array of primitives, or if you are programming in C or C++, then doing anything more is just a waste of time ▫If you are programming in Java, and the array contains objects, you should set the “deleted” array element to null ▫Why? To allow it to be garbage collected! 14 top = 2 or count = stk:

CSC 231 Sharing space Of course, the bottom of the stack could be at the other end Sometimes this is done to allow two stacks to share the same storage area 15 top = 6 or count = stk: topStk2 = stks: topStk1 = 2

CSC 231 A Stack class 16 # Implementation of a stack ADT class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def getStack(self): return self.items def main(): s = Stack() print(s.is_empty()) for n in range(7): s.push(n*10) print(s.getStack()) main()

CSC 231 Instantiating a Stack We assume that any stack class that implements this interface will also have a constructor that allows its user to create a new stack instance This is how we instantiate a stack: s = Stack() Fundamentals of Python: From First Programs Through Data Structures 17

CSC 231 Applications of Stacks We now discuss other applications of stacks: ▫Matching parentheses ▫Converting decimal numbers to binary numbers ▫Evaluating arithmetic expressions ▫Using stacks to solve backtracking problems ▫Using stacks in computer memory management Fundamentals of Python: From First Programs Through Data Structures 18

CSC 231 Example Application: Matching Parentheses Compilers need to determine if the bracketing symbols in expressions are balanced correctly Fundamentals of Python: From First Programs Through Data Structures 19

CSC 231 Example Application: Matching Parentheses (continued) Approach 1: Count left and right parentheses ▫Does not work Approach 2: ▫Scan expression; push left brackets onto a stack ▫On encountering a closing bracket, if stack is empty or if item on top of stack is not an opening bracket of the same type, we know the brackets do not balance ▫Pop an item off the top of the stack and, if it is the right type, continue scanning the expression ▫When we reach the end of the expression, stack should be empty; if not, brackets do not balance Fundamentals of Python: From First Programs Through Data Structures 20

CSC 231 Decimal to Binary Number Conversion Algorithm ▫Repeat until number is < 2  Divide number by 2 (modular arithmetic)  Place remainder on stack  Number becomes number mod 2 ▫Push number on the stack ▫Pop elements from stack and arrange so that the last element on the stack is the first digit of the binary number Fundamentals of Python: From First Programs Through Data Structures 21

CSC 231 Decimal to Binary Number Conversion In Fundamentals of Python: From First Programs Through Data Structures 22

CSC 231 Evaluating Arithmetic Expressions In the infix form of an arithmetic expression, each operator is located between its operands In the prefix form of an arithmetic expression, each operator comes immediately before its operands In the postfix form of an arithmetic expression, an operator immediately follows its operands Fundamentals of Python: From First Programs Through Data Structures 23

CSC 231 Evaluating Arithmetic Expressions infix form of an arithmetic expression ▫A + B prefix form of an arithmetic expression ▫+AB postfix form of an arithmetic expression ▫AB+ Fundamentals of Python: From First Programs Through Data Structures 24

CSC 231 Evaluating Arithmetic Expressions Fundamentals of Python: From First Programs Through Data Structures 25 Arithmetic Expressions INFIXPREFIXPOSTFIX A+B+ABAB+ A+B*C+A*BCABC*+ (A+B)*C*+ABCAB+C* A+B*C+D (A+B)*C+D (A+B)*(C+D) A*B+C*D A+B+C+D (A+B)*C-(D-E)*(F+G)

CSC 231 Algorithm for postfix Evaluating 1.Create an empty stack 2.Convert the postfix expression to a list using split 3.Scan the token list from left to right a.If the token is an operand, convert it from a string to an integer and push the value onto the stack. b.If the token is an operator, *, ?, +, -, it needs two operands. Pop the stack twice. The first pop produces the second operand and the second pop produces the first operand. c.Perform the arithmetic operation and push the result back on the stack. 4.When the list is empty, and the expression has been completely processed, the result is on the stack. Pop the stack and return the result. Fundamentals of Python: From First Programs Through Data Structures 26

CSC 231 Evaluating Arithmetic Expressions 6undamentals of Python: 6rom 6irst Programs Through 2ata Structures 27 3rithmetic Expressions INFIXPOSTFIX *5345*+ (3+4)*534+5* 3+4*5+2345*+2+ (3+4)* *2+ (3+4)*(5+2)34+52+* 3*4+5*234*52* (3+4)*5-(9-6)*(6+7) 34+5*96-67+*-

CSC 231 Pre and Post Conditions for Stack Operations Precondition – a condition that must be true before the operation executes. Postcondition – a condition that must be true after the operation executes. The Stack ADT (LIFO) ▫push(item) - add a new item to the stack.  Pre:  Post: ▫pop(item) - remove and return last item added.  Pre:  Post: ▫peek ()- remove and return last item added.  Pre:  Post: ▫isEmpty() - checks whether the stack is empty.  Pre:  Post: ▫size() - returns the number of items on the stack.  Pre:  Post: 28

CSC 231 Error checking There are two stack errors that can occur: ▫Underflow: trying to pop (or peek at) an empty stack ▫Overflow: trying to push onto an already full stack For underflow, you should throw an exception If you don’t catch it yourself, an “OutOfBound” exception my be thrown. You could create your own, more informative exception For overflow, you could do the same things Or, you could check for the problem, and copy everything into a new, larger array 29

CSC 231 Summary 30 Describe the stack ADT Understand pre and post conditions for stack operations. Apply the stack ADT to real world applications. Balancing parentheses Decimal to binary conversion Explain how the Python virtual machine uses a stack to support function and method calls

CSC ______________________ Devon M. Simmonds Computer Science Department University of North Carolina Wilmington _____________________________________________________________ Qu es ti ons? Reading for next class?

CSC 231 Pre and Post Conditions for Stack Operations Precondition – a condition that must be true before the operation executes. Postcondition – a condition that must be true after the operation executes. The Stack ADT (LIFO) ▫push(item) - adds a new item to the stack.  Pre: Stack is not full  Post: item is at the top of the stack ▫pop() - removes and return item at the top of the stack.  Pre: stack is not empty  Post: – 1 == and == item removed ▫peek ()- returns item at the top of the stack. Stack is unchanged.  Pre: None  Post: Stack unchanged ▫isEmpty() – returns True when the stack is empty.  Pre: None  Post: Stack unchanged ▫size() - returns the number of items on the stack.  Pre: None  Post: result = # of stack unchanged 32

CSC 231 Evaluating Arithmetic Expressions Fundamentals of Python: From First Programs Through Data Structures 33 Arithmetic Expressions INFIXPREFIXPOSTFIX A+B+ABAB+ A+B*C+A*BCABC*+ (A+B)*C*+ABCAB+C* A+B*C+D++A*BCDABCD*++ (A+B)*C+D+*+ABCDAB+C*D+ (A+B)*(C+D)*+AB+CDAB+CD+* A*B+C*D+*AB*CDAB*CD*+ A+B+C+D+++ABCDAB+C+D+ (A+B)*C-(D-E)*(F+G) -*+ABC*-DE+FGAB+C*DE-FG+*-

CSC 231 Algorithm for postfix Evaluating 1.Create an empty stack 2.Convert the postfix expression to a list 3.Scan the token list from left to right a.If the token is an operand, convert it from a string to an integer and push the value onto the stack. b.If the token is an operator, *, ?, +, -, it needs two operands. Pop the stack twice. The first pop produces the second operand and the second pop produces the first operand. c.Perform the arithmetic operation and push the result back on the stack. 4.When the list is empty, and the expression has been completely processed, the result is on the stack. Pop the stack and return the result. Fundamentals of Python: From First Programs Through Data Structures 34