COSC 1P03 Data Structures and Abstraction 7.1 The Stack Research is what I'm doing when I don't know what I'm doing. Wernher Von Braun (1912-1977)

Slides:



Advertisements
Similar presentations
COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Advertisements

Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks Chapter 11.
Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
Stacks Example: Stack of plates in cafeteria.
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
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.
CS 206 Introduction to Computer Science II 03 / 04 / 2009 Instructor: Michael Eckmann.
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
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 Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
E.G.M. Petrakisstacks, queues1 Stacks  Stack: restricted variant of list  elements may by inserted or deleted from only one end : LIFO lists  top: the.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
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.
1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
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
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
Topic 3 The Stack ADT.
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.
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,
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Data Structures and Algorithms
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
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.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Stack Any Other Data Structure 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)
Data Structures & Algorithms
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Click to edit Master text styles Stacks Data Structure.
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.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Stacks Chapter 5.
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
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 4.
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
Stacks Abstract Data Types (ADTs) Stacks
Introduction to Stacks
Introduction to Stacks
Stacks, Queues, and Deques
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
LINEAR DATA STRUCTURES
CHAPTER 3: Collections—Stacks
Presentation transcript:

COSC 1P03 Data Structures and Abstraction 7.1 The Stack Research is what I'm doing when I don't know what I'm doing. Wernher Von Braun ( )

COSC 1P03 Data Structures and Abstraction 7.2 Container ADTs  container  collection of objects  list-oriented collections  positional  access relative to position  e.g. list  keyed collections  have a key  accessed by key  representations  contiguous  arrays  linked  linked-structures

COSC 1P03 Data Structures and Abstraction 7.3 Stack  a list (initially empty) of items of some type to which items may be added ( push ed) at one end (called the top ) and from which items may be removed ( pop ped) only from the same end (i.e. the top)  examples  cafeteria plate stacker  Pez™ candy dispenser  behaviour  example  LIFO ordering  operations  push & pop  viewing  empty  error conditions:  underflow  overflow Pez Candy Dispenser

COSC 1P03 Data Structures and Abstraction 7.4 Character Stack ADT  item type?  say char  CharStack interface  methods  push  pop  top  empty  exceptions  NoItemException  NoSpaceException

COSC 1P03 Data Structures and Abstraction 7.5 Character Stack ADT Contiguous Implementation  representation  based on “variable-sized” array  bottom is base ( 0 th element)  top is end of collection ( n th element)  implementation  CharStacks package  instance variables  array ( elts ) and count ( top )  constructors  empty stack  methods  exceptions  defensive programming  insertion/deletion don’t affect others  O(1)

COSC 1P03 Data Structures and Abstraction 7.6 Character Stack ADT Linked Implementation  representation  top is front  list pointer points to top (front) node  implementation  instance variables  top is list pointer  constructor  empty stack  methods  exceptions  overflow?  Node wrapper class  Serializable  insert/delete at front  O(1)

COSC 1P03 Data Structures and Abstraction 7.7 Postfix (RPN) Notation  algebraic expressions  infix notation  priority  parentheses  postfix notation aka Reverse Polish Notation (RPN)  Jan Lukasiewicz  no need for parentheses or operator priorities  operator follows operands  examples  evaluate left to right  hardware computation in ALU

COSC 1P03 Data Structures and Abstraction 7.8 Infix to Postfix Translation  manual process  insert all parentheses  convert each sub-expression from inside out  remove parentheses  automated process?  desire single left to right pass over input  properties  operands in same order  operator after operands  save operator  cannot output operator until see next one  if saved is higher priority output else save next operator  at end must output saved operators in LIFO order  use a stack

COSC 1P03 Data Structures and Abstraction 7.9 Rail Yard Algorithm  operands output as seen  operator  lower/equal priority than one on stack  output stacked  higher priority than one on stack  push  open parenthesis then push, and assume lowest priority  closed parenthesis then output operators on stack and discard open parenthesis (from stack), discard closed parenthesis  when done  emit stacked operators  special cases  no operator on stack  push  have low priority operator ( $ ) at bottom of stack  end of expression  pop  have low priority operator ( # ) at end of expression

COSC 1P03 Data Structures and Abstraction 7.10 Example: InfToPost  client of CharStack  translate method  initialization  create stack ( ConCharStack or LnkCharStack )  String as char array  append #  push $  main loop  process 1 character from input at a time  operand  output  operator  output some stacked operators then push  operator priorities  relative  prio method  # & $

COSC 1P03 Data Structures and Abstraction 7.11 Generic ADTs  behaviour of stack independent of type of item  generalize interface to allow any item type  generic Stack interface  based on hypothetical content type E  generalization (abstraction) over the content type  changes from CharStack  change in name of exceptions  change from char to E throughout  addition of generic parameter after interface name  E is a type variable  Collections package  set of collection ADT (stack, queue, list, …)  common names for exceptions

COSC 1P03 Data Structures and Abstraction 7.12 Client Classes  cost of genericity  little added complexity in the client class  stacked items implement the interface of Stack  item type as E  push OK  automatic wrapping of primitive types  autoboxing  pop returns an object  primitive types are unwrapped automatically  autounboxing  Linked implementation  define Node with a generic formal type  Node is the type for Node.  E is the type for the element stored within Node  Serializable, in case we want to write the stack to disk

COSC 1P03 Data Structures and Abstraction 7.13 Type Compatibility  implements clause declares that the ActualTypeParameter for Stack is whatever is supplied as ActualTypeParameter for ConStack  thus ConStack implements Stack and ConStack implements Stack  and so in Stack opStack; opStack = new ConStack (); is valid opStack = new ConStack (); is invalid

COSC 1P03 Data Structures and Abstraction 7.14 Type Checking  how does the compiler type check within generic class, e.g. elts[top] = item;  with ConStack, Character is substituted for E so this is OK  how does compiler know?  ActualTypeParameter must be a ReferenceType  all ReferenceType s are subtypes of Object  compiler type checks assuming TypeVariable is Object  thus only operations available on the TypeVariable are those available on Object  note: compiler can still handle the elts array since it knows it is an array of some reference type and thus each element is a reference (4 bytes)

COSC 1P03 Data Structures and Abstraction 7.15  note that in the constructor: elts = (E[]) new Object[size]; is used instead of the expected elts = new E[size];  Java does not allow a type parameter to be used in an array creation expression  creating an array of Object and downcast it to E[] achieves the desired effect  enabling garbage collection  setting array elements to null allows the nodes to be garbage collected  the generic Node class  in the linked version, the Node class must be parametric since the type of the contents is unknown.  only nodes which wrap the same generic type can be put onto a list which supports a nodes of that type.  Node and Node are different types  creation of a new Node is done via top = new Node (item,top);

COSC 1P03 Data Structures and Abstraction 7.16 Example: InfToPostG  version of InfToPost using generic Stack  Chararacter  wrapper for char primitive type  algorithm the same  wrapping and unwrapping  automatic in Java 1.5 and up.  generics and templates

COSC 1P03 Data Structures and Abstraction 7.17 Java Collections Framework  Java library for data structure ADTs  java.util  stacks, queues, lists, sets, maps  Collection interface  generic in element type  operations common to all collections (except maps)  methods return boolean if the operation changed the collection (i.e. added or removed)  Stack class  generic in element type ( E )  array implementation ( Vector ) grows to fit (no overflow)  some duplication of methods (legacy implementation)  push returns item pushed

1. Load the value of x into the ALU 2. Load the value of y into the ALU 3. Apply the operator sum, x+y

Stack aStack; StudentaStudent; : aStack = new Stack (10); : aStack.push(aStudent); aStudent = aStack.pop(); Stack Creation

COSC 1P03 Data Structures and Abstraction 7.28 AutoBoxing I’m a primitive char I’m an Object Character which contains the primitive char Pointer to Character Stack can now accept the Object. Stack can only accept Objects not primitives

COSC 1P03 Data Structures and Abstraction 7.29 AutoUn-Boxing A Popped value from the stack is expected to be a primitive, in ths case a char. aChar = aStack.pop(); I’m a primitive char I’m an Object Character which contains the primitive char Pointer to Character I’m a primitive char aChar

COSC 1P03 Data Structures and Abstraction 7.30 Stack Example Input: Output:

COSC 1P03 Data Structures and Abstraction 7.31 Char Stack Interface package CharStacks; public interface CharStack { /**This method adds an item to the stack. Stack overflow occurs if there **is no room to add another item. item (char) to be added. more room to add to stack.*/ public void push ( char item ); /**This method removes an item to the stack. Stack underflow occurs if **there are no more items left. item (char) removed. items available in stack.*/ public char pop ( ); /**This method returns the top item of the stack. Stack underflow occurs **if there are no more items left. top item (char). items available in stack.*/ public char top ( ); /** This method returns true if the stack contains no items. whether the stack is empty.*/ public boolean empty ( ); } // CharStack The interface defines generic operations which support a stack architecture.

COSC 1P03 Data Structures and Abstraction 7.32 Char Stack. package CharStacks; import java.io.*; public class ConCharStack implements CharStack, Serializable { private inttop;// next available element private char[]elts;// elements of the stack public ConCharStack ( ) { this(100); };// constructor public ConCharStack ( int size ) { elts = new char[size]; top = 0; };// constructor Supported by the CharStacks Package Array holds the stack Data Structure Top always indexes the TOP element of the stack Default constructor uses chaining to create a stack that hold 100 elements Creation of the array Initial state of a Stack is empty, so TOP indexes the first element, i.e. 0

COSC 1P03 Data Structures and Abstraction 7.33 Char Stack.. public void push ( char item ) { if ( top >= elts.length ) { throw new OverflowException(); } else { elts[top] = item; top = top + 1; }; };// push public char pop ( ) { if ( top <= 0 ) { throw new UnderflowException(); } else { top = top - 1; return elts[top]; }; };// pop public char top ( ) { if ( top <= 0 ) { throw new UnderflowException(); } else { return elts[top-1]; }; };// top public boolean empty ( ) { return top <= 0; };// empty }// ConCharStack Must check if the array has room for one more element, If not then raise an exception The item is placed into the array indexed by TOP Top is incremented by 1, indexing the next available slot Must check to see if there is anything to remove, if not then raise an underflow exception The TOP indexes the next available slot, so we decrement first to index the element Return the element at TOP Must check if there is a valid element present If there is, then return the element, but leave it on the stack, Note, TOP is not modified. Boolean check, if TOP is 0 then no elements, thus empty is true

COSC 1P03 Data Structures and Abstraction 7.34 Char Stack Linked Wrapper Class Node package CharStacks; import java.io.*; /**This class represents a node in the linked structure representing **the stack. **/ class Node implements Serializable { charitem;// the item in the stack Nodenext;// the next node in the structure /**This constructor creates a new node for the linked structure **representing the stack. **/ public Node ( char i, Node n ) { item = i; next = n; };// constructor }// Node Wrapper class, Node consists of Data (item) and a next pointer. Constructor accepts the data which is a char and a link to where ‘this’ node is to point. Node’s instance variables are initialized on Node creation

COSC 1P03 Data Structures and Abstraction 7.35 Char Stack Linked. package CharStacks; import java.io.*; public class LnkCharStack implements CharStack, Serializable { private Nodetop;// top element of the stack /**This constructor creates a new, empty stack.*/ public LnkCharStack ( ) { top = null; };// constructor public void push ( char item ) { top = new Node(item,top); };// push Top is now represented by a pointer. A new stack is empty, so TOP will be null. Push is the same as an insert at front. This time the list is pointed to by TOP.

COSC 1P03 Data Structures and Abstraction 7.36 Char Stack Linked.. public char pop ( ) { chari; if ( top == null ) { throw new UnderflowException(); } else { i = top.item; top = top.next; return i; }; };// pop public char top ( ) { if ( top == null ) { throw new UnderflowException(); } else { return top.item; }; };// top public boolean empty ( ) { return top == null; };// empty }// LnkCharStack Pop must ensure there is an item to remove, A null TOP means an empty list, thus no item to remove, An exception is raised Extract the item from the node. Top moves down the list 1 node, Note this is the same as remove from front. The data item is returned. Top must still check if there is valid data at the TOP, raise exception otherwise. If there is an item in the stack then return it, but leave it on the stack (in the list). Empty is the case when TOP is null, or empty list.

COSC 1P03 Data Structures and Abstraction 7.37 Rail Yard Algorithm ((x+y)*3)/(z/(a-b)) ( ( x + y+ * 3 * / ( z / ( a - b - / /

COSC 1P03 Data Structures and Abstraction 7.38 RPN Code /**This method returns the relative priority of ** an operator. ** operator ** relative priority of c.*/ private int prio ( char c ) { switch (c) { case '$': return -1; case '#': return 0; case '+': case '-': return 1; case '*': case '/': return 2; }; return 0; // never executed };// prio For operator c, determine the relative priority and return an integer.

COSC 1P03 Data Structures and Abstraction 7.39 RPN Code. private String translate ( String in ) { charinfix[];// infix string as an array charpostfix[];// postfix result as an array intiPos;// position of next character in input intoPos;// position of next character in output charc;// next character in input CharStackopStack;// stack for operators infix = (in + '#').toCharArray(); postfix = new char[infix.length-1]; oPos = 0; opStack = new ConCharStack(5); opStack.push('$'); for ( iPos=0 ; iPos<infix.length ; iPos++ ) { c = infix[iPos]; switch (c) { case '+': case '-': case '*': case '/': case '#': while ( prio(opStack.top()) >= prio(c)) { postfix[oPos] = opStack.pop(); oPos = oPos + 1; }; opStack.push(c); break; default : postfix[oPos] = c; oPos = oPos + 1; }; return new String(postfix); };// translate Index to the output array. Create the stack and push $, This acts as a sentinel value within the stack. For each character in the input, extract one at a time, i.e. represented by c. Determine if c is an operator or not, if operand then move it to the output array postfix[oPos]. While the current operator has a lower or equal precedence then the stacked operator, pop and output. Convert the output char array to a string and return. Output is defined as a char array Append the # terminator to the input string, convert to char array, easier to process.

COSC 1P03 Data Structures and Abstraction 7.40 Generic Stack Interface package Collections; public interface Stack { /**This method adds an item to the stack. Stack overflow occurs if there **is no room to add another item. item to be added. more room to add to stack.*/ public void push ( E item ); /**This method removes an item to the stack. Stack underflow occurs if **there are no more items left. item removed. items available in stack.*/ public E pop ( ); /**This method returns the top item of the stack. Stack underflow occurs **if there are no more items left. top item. items available in stack.*/ public E top ( ); /** This method returns true if the stack contains no items. ** whether the stack is empty.*/ public boolean empty ( ); }// Stack Defines a generic type parameter We don’t know the type of item, so it is represented as a generic type Pop and Top both return types which must be represented as generic

COSC 1P03 Data Structures and Abstraction 7.41 Generic ConStack package Collections; import java.io.*; public class ConStack implements Stack, Serializable { private inttop;// next available element private E[]elts;// elements of the stack /**This constructor creates a new, empty stack capable of holding 100 **items.*/ public ConStack ( ) { this(100); };// constructor /**This constructor creates a new, empty stack capable of holding a **particular number of items. ** the number of items for the stack.*/ public ConStack ( int size ) { elts = (E[])new Object[size]; top = 0; };// constructor Part of Collections. Implement a class called Stack of some generic type E. ConStack is the implementation with the same type E which implements a Stack. “elts” thus defines an array of E, which are nothing more then objects (generic). When creating the array we are creating a set of pointers which will be of type E. Note: generics must be objects. So, elts now will be constrained to containing only elements of type E. Important to note that the type of E is known at this point since ConStack is an Object where the actual type was passed when we created the “new ConStack”.

COSC 1P03 Data Structures and Abstraction 7.42 Generic ConStack public void push ( E item ) { if ( top >= elts.length ) { throw new NoSpaceException(); } else { elts[top] = item; top = top + 1; }; };// push public E pop ( ) { Ei; if ( top <= 0 ) { throw new NoItemException(); } else { top = top - 1; i = elts[top]; elts[top] = null; return i; } };// pop public E top ( ) { if ( top <= 0 ) { throw new NoItemException(); } else { return elts[top-1]; } };// top public boolean empty ( ) { return top <= 0; };// empty }// ConStack “item” is of type E and is thus type compatible to elts. Pop returns an element of type E Anywhere the element type would be used, E is used. Since only objects are now placed on the stack, we can reclaim the memory used by elts[top] by setting this value to null.

COSC 1P03 Data Structures and Abstraction 7.43 InfToPostG (Translate) private String translate ( String in ) { charinfix[];// infix string as an array charpostfix[];// postfix result as an array intiPos;// position of next character in input intoPos;// position of next character in output charc;// next character in input Stack opStack;// stack for operators infix = (in + '#').toCharArray(); postfix = new char[infix.length-1]; oPos = 0; opStack = new ConStack (5); opStack.push('$'); for ( iPos=0 ; iPos<infix.length ; iPos++ ) { c = infix[iPos]; switch (c) { case '+': case '-': case '*': case '/': case '#': while ( prio(opStack.top()) >= prio(c)) { postfix[oPos] = opStack.pop(); oPos = oPos + 1; }; opStack.push(c)); break; default : postfix[oPos] = c; oPos = oPos + 1; }; return new String(postfix); Changes to InfToPost using a Generic Stack are marked in Blue

COSC 1P03 Data Structures and Abstraction 7.44 Generic Node Class package Collections; import java.io.*; /**This class represents a node in a singly-linked list representing a **collection. ** Hughes ** (Jan. 2005)*/ class Node implements Serializable { Eitem;// the item in the stack Node next;// the next node in the list /**This constructor creates a new node for the singly-linked list **representing a collection. ** item in the node. next node in the list.*/ public Node ( E i, Node n ) { item = i; next = n; };// constructor Part of the Collections package Node is the type, Part of this type is generic “next” must thus specify the Node as the full type of the node. Same principle applies to n. n is a pointer to a Node “item” is an element of type E.

COSC 1P03 Data Structures and Abstraction 7.45 The End