COS 312 DAY 18 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 5 Corrected – 1 A, 2 B’s, 1 C, 1 D 1 F and 1 MIA –

Slides:



Advertisements
Similar presentations
Chapter 17 Recursion.
Advertisements

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.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
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.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
1 Data Structures  We can now explore some advanced techniques for organizing and managing information  Chapter 12 of the book focuses on: dynamic structures.
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.
Chapter 4 Linked Structures. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 4-2 Chapter Objectives Describe the use of references to create.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
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 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
Chapter 12 Introduction to Collections - Stacks
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Topic 3 The Stack ADT.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 3 Introduction to Collections – Stacks Modified
Chapter 8 Lists. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine list processing and various ordering techniques.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 3: Collections Java Software Structures: Designing and Using.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 – Questions? Queues.
Chapter 6 Stacks. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine stack processing Define a stack abstract.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
Linked Structures - Review Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Linked Structures, LinkedStack
COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.
Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Collections Using Generics in Collections. 2 Chapter Objectives Define the concept and terminology related to collections Explore the basic structure.
“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 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Collections & Stacks Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 6 Corrected Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Next Capstone progress report is due April 25 Assignment 5 Graded – Not much original code Assignment.
COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Next Capstone progress report is April 25 Assignment 5 OVERDUE – Will be graded tomorrow Assignment.
Stack: a Linked Implementation
CHAPTER 4: Linked Structures
Chapter 14: 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.
Java Software Structures: John Lewis & Joseph Chase
Chapter 3 Introduction to Collections - Stacks
Chapter 4 Linked Structures - Stacks
Java Software Structures: John Lewis & Joseph Chase
Chapter 12 Recursion (methods calling themselves)
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
Stacks, Queues, and Deques
Chapter 8 Recursion.
Stacks Abstract Data Types (ADTs) Stacks
Stacks, Queues, and Deques
A type is a collection of values
CHAPTER 3: Collections—Stacks
Presentation transcript:

COS 312 DAY 18 Tony Gauvin

Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 5 Corrected – 1 A, 2 B’s, 1 C, 1 D 1 F and 1 MIA – Review of 9.3 & 9.8 (Comparable and Lockable Interfaces) Assignment 6 Posted – Due April 16 Quiz 2 Corrected – 1 A+, 3 B’s, 1 C, 1 D and 1 MIA Cont. Introduction to Collections  Stacks Begin Linked Lists

Chapter 12 Introduction to Collections - Stacks

Chapter Scope Collection terminology The Java Collections API Abstract nature of collections Stacks – Conceptually – Used to solve problems – Implementation using arrays Java Foundations, 3rd Edition, Lewis/DePasquale/Chase12 - 4

Collections A collection is an object that holds and organizes other objects It provides operations for accessing and managing its elements Many standard collections have been defined over time Some collections are linear in nature, others are non-linear Java Foundations, 3rd Edition, Lewis/DePasquale/Chase12 - 5

Abstract Data Type A data type is a group of values and the operations defined on those values An abstract data type (ADT) is a data type that isn't pre-defined in the programming language A data structure is the set of programming constructs and techniques used to implement a collection The distinction between the terms ADT, data structure, and collection is sometimes blurred in casual use Java Foundations, 3rd Edition, Lewis/DePasquale/Chase12 - 6

Stacks A stack is a classic collection used to help solve many types of problems A stack is a linear collection whose elements are added in a last in, first out (LIFO) manner That is, the last element to be put on a stack is the first one to be removed Think of a stack of books, where you add and remove from the top, but can't reach into the middle Java Foundations, 3rd Edition, Lewis/DePasquale/Chase12 - 7

Stack - Conceptual View Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stack Operations Some collections use particular terms for their operations These are the classic stack operations: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase12 - 9

Generics The generic type placeholder is specified in angle brackets in the class header: class Box { // declarations and code that refer to T } Any identifier can be used, but T (for Type) or E (for element) have become standard practice Java Foundations, 3rd Edition, Lewis/DePasquale/Chase denotes Generic Type, T will be replaced with object type when instantiated

Generics Then, when a Box is needed, it is instantiated with a specific class instead of T: Box box1 = new Box (); Now, box1 can only hold Widget objects The compiler will issue errors if we try to add a non- Widget to the box And when an object is removed from the box, it is assumed to be a Widget – BOX object will can only contain Widget objects Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Generics Using the same class, another object can be instantiated: Box box2 = new Box (); The box2 object can only hold Gadget objects Generics provide better type management control at compile-time and simplify the use of collection classes Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Exceptions When should exceptions be thrown from a collection class? Only when a problem is specific to the concept of the collection (not its implementation or its use) There's no need for the user of a collection to worry about it getting "full," so we'll take care of any such limitations internally But a stack should throw an exception if the user attempts to pop an empty stack Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

A Stack Interface Although the API version of a stack did not rely on a formal interface, we will define one for our own version To distinguish them, our collection interface names will have ADT (abstract data type) attached Furthermore, our collection classes and interfaces will be defined as part of a package called jsjf Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; /** * Defines the interface to a stack collection. * Java Foundations 4.0 */ public interface StackADT { /** * Adds the specified element to the top of this stack. element element to be pushed onto the stack */ public void push(T element); /** * Removes and returns the top element from this stack. the element removed from the stack */ public T pop(); /** * Returns without removing the top element of this stack. the element on top of the stack */ public T peek(); /** * Returns true if this stack contains no elements. true if the stack is empty */ public boolean isEmpty(); /** * Returns the number of elements in this stack. the number of elements in the stack */ public int size(); /** * Returns a string representation of this stack. a string representation of the stack */ public String toString(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase Code\chap12\jsjf\javadoc\jsjf\StackADT.html

A Stack Interface Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack with an Array Let's now explore our own implementation of a stack, using an array as the underlying structure in which we'll store the stack elements We'll have to take into account the possibility that the array could become full And remember that an array of objects really stores references to those objects Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Stacks with an Array An array of object references: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Managing Capacity The number of cells in an array is called its capacity It's not possible to change the capacity of an array in Java once it's been created Therefore, to expand the capacity of the stack, we'll create a new (larger) array and copy over the elements This will happen infrequently, and the user of the stack need not worry about it happening Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Stacks with an Array By convention, collection class names indicate the underlying structure – So ours will be called ArrayStack – java.util.Stack is an exception to this convention Our solution will keep the bottom of the stack fixed at index 0 of the array A separate integer called top will indicate where the top of the stack is, as well as how many elements are in the stack currently Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack with an Array A stack with elements A, B, C, and D pushed on in that order: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Pushing and Popping a Stack After pushing element E: After popping: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Defining an Exception An EmptyCollectionException is thrown when a pop or a peek is attempted and the stack is empty The EmptyCollectionException is defined to extend RuntimeException By passing a string into its constructor, this exception can be used for other collections as well Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf.exceptions; /** * Represents the situation in which a collection is empty. * Java Foundations 4.0 */ public class EmptyCollectionException extends RuntimeException { /** * Sets up this exception with an appropriate message. collection the name of the collection */ public EmptyCollectionException(String collection) { super("The " + collection + " is empty."); } Code\chap12\jsjf\exceptions\EmptyCollectionException.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; import jsjf.exceptions.*; import java.util.Arrays; /** * An array implementation of a stack in which the * bottom of the stack is fixed at index 0. * Java Foundations 4.0 */ public class ArrayStack implements StackADT { private final static int DEFAULT_CAPACITY = 100; private int top; private T[] stack; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Creates an empty stack using the default capacity. */ public ArrayStack() { this(DEFAULT_CAPACITY); } /** * Creates an empty stack using the specified capacity. initialCapacity the initial size of the array */ public ArrayStack(int initialCapacity) { top = 0; stack = (T[])(new Object[initialCapacity]); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Creating an Array of a Generic Type You cannot instantiate an array of a generic type directly Instead, create an array of Object references and cast them to the generic type Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified element to the top of this stack, expanding * the capacity of the array if necessary. element generic element to be pushed onto stack */ public void push(T element) { if (size() == stack.length) expandCapacity(); stack[top] = element; top++; } /** * Creates a new array to store the contents of this stack with * twice the capacity of the old one. */ private void expandCapacity() { stack = Arrays.copyOf(stack, stack.length * 2); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Removes the element at the top of this stack and returns a * reference to it. element removed from top of stack EmptyCollectionException if stack is empty */ public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("stack"); top--; T result = stack[top]; stack[top] = null; return result; } /** * Returns a reference to the element at the top of this stack. * The element is not removed from the stack. element on top of stack EmptyCollectionException if stack is empty */ public T peek() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("stack"); return stack[top-1]; } Code\chap12\jsjf\ArrayStack.javaCode\chap12\jsjf\ArrayStack.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Chapter 13 Linked Structures - Stacks

Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation of a stack Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references to create links between objects Recall that an object reference variable holds the address of an object Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Link”able” node Public class Person { private String name; private String address; private Person next; // link to another person object } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase5 - 33

Linked Structures A Person object, for instance, could contain a reference to another Person object A series of Person objects would make up a linked list: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Structures Links could also be used to form more complicated, non-linear structures Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists There are no index values built into linked lists To access each node in the list you must follow the references from one node to the next Person current = first; while (current != null) { System.out.println(current); current = current.next; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists Care must be taken to maintain the integrity of the links To insert a node at the front of the list, first point the new node to the front node, then reassign the front reference Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists To delete the first node, reassign the front reference accordingly If the deleted node is needed elsewhere, a reference to it must be established before reassigning the front pointer Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists So far we've assumed that the list contains nodes that are self-referential ( Person points to a Person ) But often we'll want to make lists of objects that don't contain such references Solution: have a separate Node class that forms the list and holds a reference to the objects being stored Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Linked Lists There are many variations on the basic linked list concept For example, we could create a doubly-linked list with next and previous references in each node and a separate pointer to the rear of the list Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stacks Revisited In the previous chapter we developed our own array-based version of a stack, and we also used the java.util.Stack class from the Java API The API's stack class is derived from Vector, which has many non-stack abilities It is, therefore, not the best example of inheritance, because a stack is not a vector It's up to the user to use a Stack object only as intended Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stacks Revisited Stack characteristics can also be found by using the Deque interface from the API The LinkedList class implements the Deque interface Deque stands for double-ended queue, and will be explored further later For now, we will use the stack characteristics of a Deque to solve the problem of traversing a maze Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Traversing a Maze Suppose a two-dimensional maze is represented as a grid of 1 (path) and 0 (wall) Goal: traverse from the upper left corner to the bottom right (no diagonal moves) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Stack algorithm for maze Start location (x,y) Repeat until Stack is empty or Maze solved (at finish location x,y) ( from current location  push all possible next moves onto stack (left, right, up and down) pop stack and move to that location ) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase5 - 44

Traversing a Maze Using a stack, we can perform a backtracking algorithm to find a solution to the maze An object representing a position in the maze is pushed onto the stack when trying a path If a dead end is encountered, the position is popped and another path is tried We'll change the integers in the maze grid to represent tried-but-failed paths (2) and the successful path (3) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*; import java.io.*; /** * Maze represents a maze of characters. The goal is to get from the * top left corner to the bottom right, following a path of 1's. Arbitrary * constants are used to represent locations in the maze that have been TRIED * and that are part of the solution PATH. * Java Foundations 4.0 */ public class Maze { private static final int TRIED = 2; private static final int PATH = 3; private int numberRows, numberColumns; private int[][] grid; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Constructor for the Maze class. Loads a maze from the given file. * Throws a FileNotFoundException if the given file is not found. * filename the name of the file to load FileNotFoundException if the given file is not found */ public Maze(String filename) throws FileNotFoundException { Scanner scan = new Scanner(new File(filename)); numberRows = scan.nextInt(); numberColumns = scan.nextInt(); grid = new int[numberRows][numberColumns]; for (int i = 0; i < numberRows; i++) for (int j = 0; j < numberColumns; j++) grid[i][j] = scan.nextInt(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Marks the specified position in the maze as TRIED * row the index of the row to try col the index of the column to try */ public void tryPosition(int row, int col) { grid[row][col] = TRIED; } /** * Return the number of rows in this maze * the number of rows in this maze */ public int getRows() { return grid.length; } /** * Return the number of columns in this maze * the number of columns in this maze */ public int getColumns() { return grid[0].length; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Marks a given position in the maze as part of the PATH * row the index of the row to mark as part of the PATH col the index of the column to mark as part of the PATH */ public void markPath(int row, int col) { grid[row][col] = PATH; } /** * Determines if a specific location is valid. A valid location * is one that is on the grid, is not blocked, and has not been TRIED. * row the row to be checked column the column to be checked true if the location is valid */ public boolean validPosition(int row, int column) { boolean result = false; // check if cell is in the bounds of the matrix if (row >= 0 && row < grid.length && column >= 0 && column < grid[row].length) // check if cell is not blocked and not previously tried if (grid[row][column] == 1) result = true; return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the maze as a string. * a string representation of the maze */ public String toString() { String result = "\n"; for (int row=0; row < grid.length; row++) { for (int column=0; column < grid[row].length; column++) result += grid[row][column] + ""; result += "\n"; } return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*; /** * MazeSolver attempts to traverse a Maze using a stack. The goal is to get from the * given starting position to the bottom right, following a path of 1's. Arbitrary * constants are used to represent locations in the maze that have been TRIED * and that are part of the solution PATH. * Java Foundations 4.0 */ public class MazeSolver { private Maze maze; /** * Constructor for the MazeSolver class. */ public MazeSolver(Maze maze) { this.maze = maze; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Attempts to traverse the maze using a stack. Inserts special * characters indicating locations that have been TRIED and that * eventually become part of the solution PATH. * row row index of current location column column index of current location true if the maze has been solved */ public boolean traverse() { boolean done = false; int row, column; Position pos = new Position(); Deque stack = new LinkedList (); stack.push(pos); while (!(done) && !stack.isEmpty()) { pos = stack.pop(); maze.tryPosition(pos.getx(),pos.gety()); // this cell has been tried if (pos.getx() == maze.getRows()-1 && pos.gety() == maze.getColumns()-1) done = true; // the maze is solved else { push_new_pos(pos.getx() - 1,pos.gety(), stack); push_new_pos(pos.getx() + 1,pos.gety(), stack); push_new_pos(pos.getx(),pos.gety() - 1, stack); push_new_pos(pos.getx(),pos.gety() + 1, stack); } return done; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Push a new attempted move onto the stack x represents x coordinate y represents y coordinate stack the working stack of moves within the grid stack of moves within the grid */ private void push_new_pos(int x, int y, Deque stack) { Position npos = new Position(); npos.setx(x); npos.sety(y); if (maze.validPosition(x,y)) stack.push(npos); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*; import java.io.*; /** * MazeTester determines if a maze can be traversed. * Java Foundations 4.0 */ public class MazeTester { /** * Creates a new maze, prints its original form, attempts to * solve it, and prints out its final form. */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(System.in); System.out.print("Enter the name of the file containing the maze: "); String filename = scan.nextLine(); Maze labyrinth = new Maze(filename); System.out.println(labyrinth); MazeSolver solver = new MazeSolver(labyrinth); if (solver.traverse()) System.out.println("The maze was successfully traversed!"); else System.out.println("There is no possible path."); System.out.println(labyrinth); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links Let's now implement our own version of a stack that uses a linked list to hold the elements Our LinkedStack class stores a generic type T and implements the same StackADT interface used previously A separate LinearNode class forms the list and hold a reference to the element stored An integer count will store how many elements are currently in the stack Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links Since all activity on a stack happens on one end, a single reference to the front of the list will represent the top of the stack Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links The stack after A, B, C, and D are pushed, in that order: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links After E is pushed onto the stack: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; /** * Represents a node in a linked list. * Java Foundations 4.0 */ public class LinearNode { private LinearNode next; private T element; /** * Creates an empty node. */ public LinearNode() { next = null; element = null; } /** * Creates a node storing the specified element. elem element to be stored */ public LinearNode(T elem) { next = null; element = elem; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the node that follows this one. reference to next node */ public LinearNode getNext() { return next; } /** * Sets the node that follows this one. node node to follow this one */ public void setNext(LinearNode node) { next = node; } /** * Returns the element stored in this node. element stored at the node */ public T getElement() { return element; } /** * Sets the element stored in this node. elem element to be stored at this node */ public void setElement(T elem) { element = elem; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

package jsjf; import jsjf.exceptions.*; import java.util.Iterator; /** * Represents a linked implementation of a stack. * Java Foundations 4.0 */ public class LinkedStack implements StackADT { private int count; private LinearNode top; /** * Creates an empty stack. */ public LinkedStack() { count = 0; top = null; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified element to the top of this stack. element element to be pushed on stack */ public void push(T element) { LinearNode temp = new LinearNode (element); temp.setNext(top); top = temp; count++; } /** * Removes the element at the top of this stack and returns a * reference to it. element from top of stack EmptyCollectionException if the stack is empty */ public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("stack"); T result = top.getElement(); top = top.getNext(); count--; return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing a Stack using Links Java Foundations, 3rd Edition, Lewis/DePasquale/Chase