Stacks as an Abstract Data Type CS1316: Representing Structure and Behavior.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Stacks, Queues, and Linked Lists
Discrete Event Simulation CS1316: Representing Structure and Behavior.
Stack & Queues COP 3502.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
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.
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.
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
CS Data Structures II Review COSC 2006 April 14, 2017
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
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.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
CS 106 Introduction to Computer Science I 12 / 11 / 2006 Instructor: Michael Eckmann.
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.
Stack: Linked List Implementation Push and pop at the head of the list New nodes should be inserted at the front of the list, so that they become the top.
30-Jun-15 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.
CS 106 Introduction to Computer Science I 12 / 13 / 2006 Instructor: Michael Eckmann.
1 Lecture 26 Abstract Data Types – IV Overview  The List ADT  Implementing Stacks as Linked List  Linked List Implementation of Queues .  Preview:
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
Chapter 7 Stacks II CS Data Structures I COSC 2006
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
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,
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Lists ADT (brief intro):  Abstract Data Type  A DESCRIPTION of a data type  The data type can be anything: lists, sets, trees, stacks, etc.  What.
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.
CSC 212 Stacks & Queues. Announcement Many programs not compiled before submission  Several could not be compiled  Several others not tested with javadoc.
Problem Solving with Data Structures using Java: A Multimedia Approach
1/ 124 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 18 Programming Fundamentals using Java 1.
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.
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,
Pointers OVERVIEW.
Data Structures (part 2). Stacks An Everyday Example Your boss keeps bringing you important items to deal with and keeps saying: “Put that last ‘rush’
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
Pertemuan 24 DISCRETE-EVENT SYSTEM SIMULATION Matakuliah: D0174/ Pemodelan Sistem dan Simulasi Tahun: Tahun 2009.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
Stacks The content for these slides was originally created by Gerard Harrison. Ported to C# by Mike Panitz.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Introduction to Data Structures and Algorithms
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
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.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Data Structures Intro2CS – week Stack ADT (Abstract Data Type) A container with 3 basic actions: – push(item) – pop() – is_empty() Semantics: –
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.
Sorted Linked List Same objective as a linked list, but it should be sorted Sorting can be custom according to the type of nodes Offers speedups over non-sorted.
Building Java Programs
Queues Queues Queues.
Cinda Heeren / Geoffrey Tien
Stack and Queue APURBO DATTA.
Pointers and Linked Lists
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Building Java Programs
Stacks as an Abstract Data Type
More Data Structures (Part 1)
Stacks CS-240 Dick Steflik.
Lists.
Building Java Programs
Stacks, Queues, and Deques
Lecture 7: Linked List Basics reading: 16.2
Stacks.
Presentation transcript:

Stacks as an Abstract Data Type CS1316: Representing Structure and Behavior

Story Stack: Another useful kind of list An example of an Abstract Data Type (ADT): We can define the methods and the behavior apart from any implementation. There are multiple implementations, some better than others. Can use a stack to reverse a list in less time, but more space. A classic tradeoff! Space for time.

Key idea #1: Introducing a Queue Last-In-First-Out List First item in the list is the last one out. Last one in is first one out. I got here first! I got here second! I got here third! This is the top of the stack

New items go at the top I got here first! I got here second! I got here third! This is the new top of the stack I got here fourth!

Items only get removed from the top I got here first! I got here second! I got here third! This is the new (er, old) top of the stack I got here fourth! And now I’m outta here!

What can we do with stacks? push(anObject): Tack a new object onto the top of the queue pop(): Pull the top (head) object off the queue. peek(): Get the top of the queue, but don’t remove it from the queue. size(): Return the size of the queue

Example stack Welcome to DrJava. > Stack stack = new Stack() > stack.push("This") > stack.push("is") > stack.push("a") > stack.push("test") > stack.size() 4 > stack.peek() "test" > stack.pop() "test" > stack.pop() "a" > stack.pop() "is" > stack.pop() "This" > stack.pop() java.util.NoSuchElementException: Notice anything interesting about the order in and the order out?

Implementing a stack with a linked list import java.util.LinkedList; // Need for LinkedList public class Stack { /** Where we store the elements */ private LinkedList elements; /// Constructor //// public Stack() { elements = new LinkedList(); }

Stack methods //// Methods /// public void push(Object element){ // New elements go at the front elements.addFirst(element); } public Object peek(){ return elements.getFirst(); } public Object pop(){ Object toReturn = this.peek(); elements.removeFirst(); return toReturn; } public int size(){return elements.size();}

A stack is a stack, no matter what lies beneath. Our description of the stack minus the implementation is an example of an abstract data type (ADT). An abstract type is a description of the methods that a data structure knows and what the methods do. We can actually write programs that use the abstract data type without specifying the implementation. There are actually many implementations that will work for the given ADT. Some are better than others.

Building a Stack from an Array /** * Implementation of a stack as an array **/ public class Stack2 { private static int ARRAYSIZE = 20; /** Where we'll store our elements */ private Object[] elements; /** Index where the top of the stack is */ private int top;

Stack2 = array + top index /// Constructor //// public Stack2() { elements = new Object[ARRAYSIZE]; top = 0; }

Stack2 Methods //// Methods /// public void push(Object element){ // New elements go at the top elements[top]=element; // then add to the top top++; if (top==ARRAYSIZE){ System.out.println("Stack overflow!"); } public Object peek(){ if (top==0){ System.out.println("Stack empty!"); return null; } else{ return elements[top-1];} } public Object pop(){ Object toReturn = this.peek(); top--; return toReturn; } /** Size is simply the top index */ public int size(){return top;}

Testing Stack2 Welcome to DrJava. > Stack2 stack = new Stack2(); > stack.push("Matt") > stack.push("Katie") > stack.push("Jenny") > stack.size() 3 > stack.peek() "Jenny" > stack.pop() "Jenny" > stack.pop() "Katie" > stack.pop() "Matt" > stack.pop() Stack empty! null

What are stacks good for? The algorithm for converting an equation into a tree uses a stack. As new functions get called, position in old functions get pushed on a stack. So you always return to the last function you were in. If an error occurs, you get a stack trace. If your recursion goes into an infinite loop, what error do you get? Stack overflow!

A Stack Example: New Reverse Recall our original implementation of reverse(). We go to the end of the original list to find the last(). We then remove() it (which involves walking the list until we find the one before last()) We then insert it at the end of the new list (via add(), which does last().insertAfter()). All told: For each node, we walk the whole list three times. O(n*n 2 )=O(n 3 )

Original Reverse /** * Reverse the list starting at this, * and return the last element of the list. * The last element becomes the FIRST element * of the list, and THIS goes to null. **/ public LLNode reverse() { LLNode reversed, temp; // Handle the first node outside the loop reversed = this.last(); this.remove(reversed); while (this.getNext() != null) { temp = this.last(); this.remove(temp); reversed.add(temp); }; // Now put the head of the old list on the end of // the reversed list. reversed.add(this); // At this point, reversed // is the head of the list return reversed; }

Testing Reverse in SoundListTest() public void reverseTest(){ FileChooser.setMediaPath("D:/cs1316/MediaSources/"); Sound s = null; // For copying in sounds s = new Sound(FileChooser.getMediaPath("guzdial.wav")); SoundNode root = new SoundNode(s); s = new Sound(FileChooser.getMediaPath("is.wav")); SoundNode one = new SoundNode(s); root.last().insertAfter(one); s = new Sound(FileChooser.getMediaPath("scritch-q.wav")); SoundNode two = new SoundNode(s); root.last().insertAfter(two); s = new Sound(FileChooser.getMediaPath("clap-q.wav")); SoundNode three = new SoundNode(s); two.insertAfter(three); //root.playFromMeOn(); SoundNode reversed = (SoundNode) root.reverse2(); reversed.playFromMeOn(); }

Stack-based Reverse /** * Reverse2: Push all the elements on * the stack, then pop all the elements * off the stack. **/ public LLNode reverse2() { LLNode reversed, current, popped; Stack stack = new Stack(); current=this; while (current != null) { stack.push(current); current = current.getNext(); } reversed = (LLNode) stack.pop(); current = reversed; while (stack.size()>0) { popped=(LLNode) stack.pop(); current.insertAfter(popped); current = popped; } return reversed; }

What’s the diff? Time How often is each node touched in reverse2()? Twice: Once going onto the stack, once coming off. O(2*n) => O(n) The stack-based reverse is faster than the original reverse.

What’s the diff? Space How much space does reverse2() take? Whatever space the stack takes. How much additional space does reverse() take? None Very common tradeoff: Space for time. You can make an algorithm go faster, by using more space. If you need to fit into less memory, you have to do more processing, which takes more time.