USING STACKS

Embed Size (px)

Citation preview

  • 8/9/2019 USING STACKS

    1/14

    6. 94 USING STACKS CS2310 DSAJ 2014/2015

    Unit 6. Stacks and their Applications

    Outcomes Summary. You will:

    -consider some uses of stacks

    -consider implementations of stack as provided by J2SDK.

    92 Unit Objectives

    Examinestackprocessing.

    Demonstrate how a stack can be used to solve practical problems.

    Examine various implementations of stack in J2SDK.

    93 Introduction

    In Unit 3, we discussed the StackADT and, in Unit 4, looked at a simple array-based implementa-tion of this ADT: namely ArrayStack. In Unit 5, we looked at a straight-forward implementationofStackADT using a linked list. In this unit, we will examine the use of stack to solve certain typesof programming problems.

    94 Using Stacks

    Stacks are particularly helpful when solving certain types of problems in Computer Science.

    One common application of a stack is to implement a multipleundofacility in an application.In order to performundo operations, the application needs to keep track of the sequence ofrecent operations in reverseorder. When an operation is performed, a record of it is pushedonto a stack and when theundofunction is invoked, the most recent operation can be poppedoff the stack for undoing.

    A classic use of stacks is in the run-time environment of a programming language such as Java.As method calls occur, the run-time system pushes anactivation recordonto the run-time stack.When each method completes its execution, itsactivation recordispoppedoff the stack and usinginformation in this record control returns to the method that called it. The activation record

    on the top of the stack corresponds to the executing method. Hence,the run-time system canroll back the chain of method calls as each called method finishes its execution by poppingthe activation record off the top of the stack.

    Another suitable use of a stack is for keeping track ofalternativesin maze traversal or in othertrial and error algorithms.

    Stacks are also useful in an application that evaluatespostfix expressions.

    We will consider these last two examples in more detail below.

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 1/14

  • 8/9/2019 USING STACKS

    2/14

    6. 95 TRAVERSING A MAZE USING A STACK CS2310 DSAJ 2014/2015

    95 Traversing a Maze using a Stack

    We can traverse a maze using atrial-and-errorapproach. We need to use a stack to keep track ofmoves that have not yet been tried in order to avoid repeatedly trying paths that have already

    been followed.

    A maze can be represented by a grid of1s and 0s. A 0represents a blockage (i.e. part of awall) and a1 represents a path. Thus the grid can be represented as a two-dimensional arrayofint values in Java. A successful traversal of the maze means that a continuous path of1sis found from the starting point (the top left corner of the grid in our example) to the finishingpoint (the bottom right corner of the grid). See Figure 44.

    Figure 44: A path in a maze.

    During the maze traversal, we need to remember the positions that have been already visited.As we visit each valid location, we change the1stored there to a3to mark it as visited. Subse-quently, the marked locations are discounted when looking for valid moves (See Figure 45 &

    the methodtraverse()in the classMaze).

    Figure 45: The maze after traversal.

    At each point of the traversal, we can find up to four potential moves: the positions on theleft, on the right, above and below the current position25. Not all four possible moves needto be valid; this will be the case if we are at at an edge or corner of the grid or if some of theneighbouring positions are walls or are positions that have already been visited. We keep trackof thevalidmoves by pushing the end position of each valid move onto the stack. For example,given the maze in Figure 44, there are two valid moves from the position (0, 0)):

    1. to position(1, 0)

    2. to position(0, 1)25diagonal moves are not allowed

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 2/14

  • 8/9/2019 USING STACKS

    3/14

    6. 95 TRAVERSING A MAZE USING A STACK CS2310 DSAJ 2014/2015

    We push these positions onto the stack (see the methods traverse, valid and push new posin the class Maze). The order in which the possible valid moves are pushed onto the stack isnot critical; the algorithm works whatever the order.

    When we want to make a move, we pop one position from the stack and move to this position.(See the method traversein the class Maze). As we move on, more valid moves are found

    and pushed into the stack and one by one positions are marked as visited. At each move, wepop one location from the stack. In this way, the maze traversal is carried out until the targetlocation is reached (or if there is no possible path from start to finish until the stack is emptyand no valid moves remain). There is no chance of getting into an infinite loop as alreadyvisited cells are never revisited.

    Note that this implementation of maze search enables the target location to be found, but thepath which leads from the start position to the finish isnotrecorded by the algorithm.

    The Java solution consists of three tailor-written classes plus an implementation of the interfaceStackADT. Figure 46 shows the class ArrayStack as the implementing class, but the classLinkedStack

    could be used instead with only minor changes to the code. (Exercise!).

    Figure 46: A UML class diagram for the maze traversal application

    ClassMaze

    1 package maze;

    2

    3 /**4 * Maze.java

    5 *6 * Represents a maze of characters. The goal is to get from the

    7 * top left corner to the bottom right, following a path of 1s.

    8 *9 * @author Lewis/Chase

    10 * @author S H S Wong

    11 * @author A Barnes

    12 * @version 10-2009

    13 */

    14 import dsaj.*;

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 3/14

  • 8/9/2019 USING STACKS

    4/14

    6. 95 TRAVERSING A MAZE USING A STACK CS2310 DSAJ 2014/2015

    15

    16 public class Maze {

    17 // For Marking a location within the maze that has been visited.

    18 private final int TRIED = 3;

    19 private Position start = new Position(0, 0);

    20 private Position finish = new Position(8, 12);

    2122 // The maze as represented by a 2D grid.

    23 private int[][] grid =

    24 { { 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1 },

    25 { 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 },

    26 { 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0 },

    27 { 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1 },

    28 { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1 },

    29 { 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1 },

    30 { 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },

    31 { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },

    32 { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };

    33

    34 StackADT stack = new ArrayStack(200);

    35

    36 /*37 * A method for pushing a new position onto the stack. A new position (x,

    38 * y) is pushed onto the stack ONLY IF it is a valid position that is it

    39 * is inside the grid, is not a wall and has not been visited already.

    40 */

    41 private void push_new_pos(int x, int y) {

    42 if (valid(x, y)) {

    43 stack.push(new Position(x, y));

    44 }

    45 }

    46

    47 /*******************************************************************48 * Attempts to iteratively traverse the maze. It inserts special

    49 * characters indicating locations that have been tried and that

    50 * eventually become part of the solution. This method uses a

    51 * stack to keep track of the possible moves that could be made.

    52 ******************************************************************* /

    53 public boolean traverse() {

    54 boolean done = false; // set true when the finish position is reached

    55 Position pos;

    56 stack.push(start);

    57

    58 while (!(done)) {

    59 pos = stack.pop();

    60 grid[pos.getX()][pos.getY()] = TRIED; // this cell has been tried

    61 if (pos.getX() == finish.getX() && pos.getY() == finish.getY())

    62 done = true; // the maze is solved

    63 else {

    64 /*65 * Get the four positions that are adjacent to the current

    66 * position, i.e. the positions on the left, on the right,

    67 * above and below the current position. These correspond

    68 * to the potential moves. Each of such position is analysed

    69 * to see if it is a valid move. Only valid moves will be

    70 * pushed onto the stack.

    71 */72 push_new_pos(pos.getX(), pos.getY() - 1);

    73 push_new_pos(pos.getX(), pos.getY() + 1);

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 4/14

  • 8/9/2019 USING STACKS

    5/14

    6. 95 TRAVERSING A MAZE USING A STACK CS2310 DSAJ 2014/2015

    74 push_new_pos(pos.getX() - 1, pos.getY());

    75 push_new_pos(pos.getX() + 1, pos.getY());

    76 }

    77 }

    78 return done;

    79 }

    8081 // Determines if a specific location is valid.

    82 private boolean valid(int row, int column) {

    83 boolean result = false;

    84

    85 /* Check if cell is in the bounds of the maze */

    86 if (row >= 0 && row < grid.length && column >= 0

    87 && column < grid[row].length)

    88

    89 /* Check if cell is not blocked and not previously tried */

    90 if (grid[row][column] == 1)

    91 result = true;

    92

    93 return result;

    94 }

    95

    96 // Returns the maze as a string.

    97 public String toString() {

    98 String result = "\n";

    99

    100 // Print the grid line by line

    101 for (int row = 0; row < grid.length; row++) {

    102 // Print each element in a line

    103 for (int column = 0; column < grid[row].length; column++)

    104 result += grid[row][column] + "";

    105

    106 result += "\n";

    107 }

    108 return result;

    109 }

    110 }

    ClassPosition

    1 package maze;

    2

    3 /**

    4 * Position.java5 * Represents a single position in a rectangular grid

    6 *7 * @author Lewis/Chase

    8 * @author A Barnes

    9 * @author S H S Wong

    10 * @version 24-10-2010

    11 */

    12 public class Position {

    13 private int x;

    14 private int y;

    15

    16 /**17 * Constructs a position and sets the x and y coordinates

    18 * @param x X coordinate of a position

    19 * @param y Y coordinate of the position

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 5/14

  • 8/9/2019 USING STACKS

    6/14

    6. 95 TRAVERSING A MAZE USING A STACK CS2310 DSAJ 2014/2015

    20 */

    21 Position(int x, int y) {

    22 this.x = x;

    23 this.y = y;

    24 }

    25

    26 /**27 * Returns the x-coordinate value of the current position.

    28 * @return the X coordinate of the current position

    29 */

    30 public int getX() {

    31 return x;

    32 }

    33

    34 /**35 * Returns the y-coordinate value of the current position.

    36 * @return the Y coordinate of the current position

    37 */

    38 public int getY() {

    39 return y;

    40 }

    41 }

    ClassMazeSearch

    1 package maze;

    2 /**3 * MazeSearch.java

    4 * Top-level class for the maze-search application.

    5 * This application simulates the process of finding a path of 1s in a

    6 * maze of characters (represented by 1s and 0s).

    7 *8 * @author Lewis/Chase

    9 * @author S H S Wong

    10 * @version 24-10-2010

    11 */

    12 public class MazeSearch {

    13 /*******************************************************************14 * Creates a new maze, prints its original form, attempts to solve it,

    15 * and prints out its final form.

    16 ******************************************************************* /

    17 public static void main(String[] args) {

    18 // Create the maze.

    19 Maze labyrinth = new Maze();20

    21 /*22 * Print the maze. At the beginning, the maze contains 0s (i.e.

    23 * blockage) & 1s (i.e. path) only.

    24 */

    25 System.out.println(labyrinth);

    26

    27 /*28 * labyrinth.traverse() is for traversing the maze. When a path is

    29 * found at the end of the maze traversal, the value true is returned.

    30 * Otherwise, false is returned.

    31 */

    32 if (labyrinth.traverse())

    33 System.out.println("The maze was successfully traversed!");

    34 else

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 6/14

  • 8/9/2019 USING STACKS

    7/14

    6. 96 EVALUATING POSTFIX EXPRESSIONS USING A STACK CS2310 DSAJ 2014/2015

    35 System.out.println("There is no possible path.");

    36

    37 /*38 * Print the maze after the traversal has taken place. As during the

    39 * traversal, each visited position is marked with 3, the maze should

    40 * now contain 0s, 1s & 3s.

    41 */42 System.out.println(labyrinth);

    43 }

    44 }

    96 Evaluating Postfix Expressions using a Stack

    In representing a mathematical expression, we generally use infixnotation, with parenthesesto indicate precedence, e.g.:

    (3+4) 2

    In a postfix expression, the operator comesafterits twooperands26 and parentheses are neverneeded to determine precedence.

    Inpostfixnotation, the above expression would be written as 3 4+2.

    Postfix expressions can be evaluated with the aid of a stack for storing the operands and partialresults of the computation.

    Evaluating a postfix expression involves the following:

    Scan from left to right, determining if the next token in the input expression is an operator

    or operand.

    If it is an operand,pushit on the stack.

    If it is an operator,popthe stacktwiceto get the two operands, perform the operation on thetwo operands, and push the result back onto the stack.

    At the end, there will beonevalue on the stack, which is the value of the expression (assumingthe input represents a valid postfix expression).

    Figure 47 shows an example of the sequence of processes for evaluating a postfix expressionusing astack. This postfix expression, when written in aninfixform, is:

    7 (4 3)/(1+5)

    Figure 47: Using a stack to evaluate a postfix expression

    26For simplicity we only consider binary operators (i.e. those taking two operands).

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 7/14

  • 8/9/2019 USING STACKS

    8/14

    6. 96 EVALUATING POSTFIX EXPRESSIONS USING A STACK CS2310 DSAJ 2014/2015

    The class Postfix is a Java application for a simple command-line-based postfix evaluator.This application demonstrates how a stack data structure can be used to aid the evaluation ofpostfix expressions.

    To simplify the example, let us assume that the operands of the expressions are integerliterals.This means that the stack in this application will work with Integerobjects only.

    In order not to cloud the presentation with try ... catch blocks, we will assume theinput is a syntactically correct postfix expression.

    1 package postfix;

    2 //********************************************************************3 //Postfix.java Authors: Lewis/Chase (Modified by Wong)

    4 //

    5 //Demonstrates the use of a stack to evaluate postfix expressions.

    6 //********************************************************************7 import java.util.Scanner;

    8

    9 public class Postfix

    10 {11 /*******************************************************************12 Reads and evaluates multiple postfix expressions.

    13 ******************************************************************* /

    14 public static void main (String[] args)

    15 {

    16 String expression, again;

    17 int result;

    18

    19 try

    20 { /* A Scanner breaks its input into tokens using

    21 * a delimiter pattern. A whitespace character is the

    22 * default delimit pattern for a Scanner object.23 */

    24 Scanner in = new Scanner(System.in);

    25

    26 do

    27 {

    28 PostfixEvaluator evaluator = new PostfixEvaluator();

    29 System.out.println ("Enter a valid postfix expression: ");

    30 expression = in.nextLine();

    31

    32 result = evaluator.evaluate (expression);

    33 System.out.println();

    34 System.out.println ("That expression equals " + result);

    35

    36 System.out.print ("Evaluate another expression [Y/N]? ");

    37 again = in.nextLine();

    38 System.out.println();

    39 }

    40 while (again.equalsIgnoreCase("y"));

    41 }

    42 catch (Exception IOException)

    43 {

    44 System.out.println("Input exception reported");

    45 }

    46 }

    47 }

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 8/14

  • 8/9/2019 USING STACKS

    9/14

    6. 96 EVALUATING POSTFIX EXPRESSIONS USING A STACK CS2310 DSAJ 2014/2015

    This Java application uses a LinkedStackobject to model the stack, i.e. a stack modelled asa linear linked structure. As far as the application is concerned, any implementation of a stackwould suffice.

    The class PostfixEvaluator uses a LinkedStack object to evaluate a string representationof posfix expressions. A PostfixEvaluator object is used by the class Postfix, which

    defines a simple text-based interface for obtaining a postfix expression entered by the user viathe standard input stream.

    1 package postfix;

    2 //********************************************************************3 //PostfixEvaluator.java Authors: Lewis/Chase (Modified by Wong)

    4 //

    5 //Represents an integer evaluator of postfix expressions. Assumes

    6 //the operands are constants.

    7 //********************************************************************8 import dsaj.*;

    9 import java.util.StringTokenizer;

    10

    11 public class PostfixEvaluator {

    12 private final char ADD = +;

    13 private final char SUBTRACT = -;

    14 private final char MULTIPLY = *;

    15 private final char DIVIDE = /;

    16 private final char REMAINDER = %;

    17 private StackADT stack;

    18

    19 /*******************************************************************20 Sets up this evaluator by creating a new stack.

    21 ******************************************************************* /

    22 public PostfixEvaluator() {

    23 stack = new LinkedStack();24 }

    25

    26 /*******************************************************************27 Evaluates the specified postfix expression. If an operand is

    28 encountered, it is pushed onto the stack. If an operator is

    29 encountered, two operands are popped, the operation is

    30 evaluated, and the result is pushed onto the stack.

    31 ******************************************************************* /

    32 public int evaluate(String expr) {

    33 int op1, op2, result = 0;

    34 String token;

    35 /*

    Use a StringTokenizer object for breaking the input string

    36 * into tokens.

    37 */

    38 StringTokenizer tokenizer = new StringTokenizer (expr);

    39

    40 /* Keep processing each tokens in the input string

    41 * when there are more tokens to process.

    42 */

    43 while (tokenizer.hasMoreTokens()) {

    44 // Get the next token from the input string.

    45 token = tokenizer.nextToken();

    46

    47 /* If this token is an operator (i.e. +, -, / or *),

    48 * pop two integers from the stack and calculate the result.49 * Push the result into the stack after the calculation.

    50 *

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 9/14

  • 8/9/2019 USING STACKS

    10/14

    6. 96 EVALUATING POSTFIX EXPRESSIONS USING A STACK CS2310 DSAJ 2014/2015

    51 * Java 5.0 or above has built-in automatic type conversation

    52 * between primitive values and their corresponding wrapper

    53 * class values (e.g. int Integer), so we dont need to do

    54 * explicit type conversation when popping elements out of

    55 * our stack.

    56 */

    57 if (isOperator(token)) {58 op2 = stack.pop();

    59 op1 = stack.pop();

    60 result = evalSingleOp (token.charAt(0), op1, op2);

    61 stack.push (result);

    62 }

    63 else

    64 /* If not, this token must be an integer.

    65 * Convert it into an int type and

    66 * push it into the stack.

    67 */

    68 stack.push (Integer.parseInt(token));

    69 }

    70

    71 return result;

    72 }

    73

    74 /*******************************************************************75 Determines if the specified token is an operator.

    76 ******************************************************************* /

    77 private boolean isOperator (String token) {

    78 return ( token.equals("+") || token.equals("-") ||

    79 token.equals("*") || token.equals("/") || token.equals("%") );

    80 }

    81

    82 /*******************************************************************83 Peforms integer evaluation on a single expression consisting of

    84 the specified operator and operands.

    85 ******************************************************************* /

    86 private int evalSingleOp (char operation, int op1, int op2) {

    87 int result = 0;

    88

    89 switch (operation) {

    90 case ADD:

    91 result = op1 + op2;

    92 break;

    93 case SUBTRACT:

    94 result = op1 - op2;

    95 break;

    96 case MULTIPLY:

    97 result = op1 * op2;

    98 break;

    99 case DIVIDE:

    100 result = op1 / op2;

    101 break;

    102 case REMAINDER:

    103 result = op1 % op2;

    104 }

    105

    106 return result;

    107 }108 }

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 10/14

  • 8/9/2019 USING STACKS

    11/14

    6. 97 CLASS JAVA.UTIL.STACK CS2310 DSAJ 2014/2015

    97 Classjava.util.Stack

    Class java.util.Stack is part of JDK since version 1.0. The Java Platform Standard Edition7 API Specification states (http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html):

    The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector withfive operations that allow a vector to be treated as a stack. The usual push and pop operations areprovided, as well as a method to peek at the top item on the stack, a method to test for whether thestack is empty, and a method to search the stack for an item and discover how far it is from the top.

    When a stack is first created, it contains no items.

    J2SDK 7 defines a Stackclass27 with operations such aspop, push, peekand empty(i.e. totest if the stack is empty).

    java.util.Stack extends java.util.Vector28 and therefore has some characteristics

    that are not appropriate for a pure stack. For example, it inheritsmethods like: add

    ,addAll

    ,addElement, capacity, contains, elementAt, indexOf, insertElementAt, remove,removeAll, subList, trimToSize, etc. which violate the characteristic of a stack, i.e. accessof elements can only be done from the top of the stack.

    Furthermore, the method searchin java.util.Stacksearches through the stack and re-turns whether the specified element exists in the stack, and, if so, its whereabout. As stackshave openning at one end only, users of a stack should not be able to inspect the elements inthe stack, unless the element is at the top.

    Classes java.util.Stackand java.util.Vectorhave been around since the originalversion of Java (i.e. JDK 1.0). While java.util.Stack is not part of the Java Collections

    Framework (JCF),java.util.Vector

    has been retrofitted to implement thejava.util.List

    interface, making it a member of the JCF since version 1.2.

    Figure 48: java.util.Stackextends java.util.Vectorand implements six different inter-faces.

    One way to reuse java.util.Stack as a pure stack is by means of a wrapper class. Anapplication programmer may define a wrapper class named PureStack, say, which has asingle field contents of type java.util.Stack. Class PureStack can define methodsthat belongs to a pure stack, e.g. pop, push, peek and isEmpty. Each of these methodssimply calls the respective method in java.util.Stackto do the job.

    27See API for details (http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html).28Class Vectorimplements a growable array of objects. http://docs.oracle.com/javase/7/docs/api/

    java/util/Vector.html

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 11/14

  • 8/9/2019 USING STACKS

    12/14

    6. 99 CLASS JAVA.UTIL.ARRAYDEQUE CS2310 DSAJ 2014/2015

    98 Interfacejava.util.Deque

    The Java Platform Standard Edition 7 API Specification states (http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html):

    Interface java.util.Dequeis a linear collection that supports element insertion and re-moval at both ends. The name deque is short for double ended queue and is usually pronounceddeck. Most Deque implementations place no fixed limits on the number of elements they maycontain, but this interface supports capacity-restricted deques as well as those with no fixed sizelimit.

    This interface defines methods to access the elements at both ends of the deque. Methods areprovided to insert, remove, and examine the element. Each of these methods exists in two forms:one throws an exception if the operation fails, the other returns a special value (either null or false,depending on the operation). The latter form of the insert operation is designed specifically for usewith capacity-restricted Deque implementations; in most implementations, insert operations cannot

    fail.

    Deques can be used as LIFO (Last-In-First-Out) stacks. This interface should be used in prefer-ence to the legacy Stack class. When a deque is used as a stack, elements are pushed and popped fromthe beginning of the deque. Stack methods are precisely equivalent to Deque methods as indicated inthe table below:

    Stack Method Equivalent Deque Method

    push(e) addFirst(e)pop() removeFirst()peek() peekFirst()

    java.util.Dequehas been introduced to the JCF since Java 1.6.

    java.util.Deque is designed to be a multi-purpose collection. It is expected to be used as astack or a queue.

    99 Classjava.util.ArrayDeque

    The Java Platform Standard Edition 7 API Specification states (http://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html):

    Classjava.util.ArrayDequeis aresizable-array implementation of the Deque interface.

    Array deques have no capacity restrictions; they grow as necessary to support usage. . . . Null ele-ments are prohibited. This class is likely to be faster than Stackwhen used as a stack, and fasterthanLinkedListwhen used as a queue.

    Most ArrayDequeoperations run in amortized constant time. Exceptions include remove,removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(),and the bulk operations, all of which run in linear time.

    Classjava.util.ArrayDeque implements the java.util.Dequeinterface. Hence, it canbe used as a stack, but the application programmer who uses it will need to stick to the stack-only methods in this class, i.e. addFirst,removeFirstand peekFirst.

    Classjava.util.ArrayDequeis in the JCF since Java 1.6.

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 12/14

  • 8/9/2019 USING STACKS

    13/14

    6. 101 CLASSJAVA.UTIL.LINKEDLIST CS2310 DSAJ 2014/2015

    100 Classjava.util.LinkedBlockingDeque

    The Java Platform Standard Edition 7 API Specification states (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingDeque.html):

    Class java.util.LinkedBlockingDequeis an optionally-bounded blocking deque basedon linked nodes.The optional capacity bound constructor argument serves as a way to prevent excessive expan-

    sion. The capacity, if unspecified, is equal to Integer.MAX VALUE. Linked nodes are dynamicallycreated upon each insertion unless this would bring the deque above capacity.

    Most operations run in constant time (ignoring time spent blocking). Exceptions include re-move, removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk op-erations, all of which run in linear time.

    Class java.util.LinkedBlockingDequeimplements the java.util.Deque interface.Hence, it can be used as a stack, but the application programmer who uses it will need to stick

    to the stack-only methods in this class, i.e. addFirst,removeFirstand peekFirst.

    Classjava.util.LinkedBlockingDequeis in the JCF since Java 1.6.

    101 Classjava.util.LinkedList

    The Java Platform Standard Edition 7 API Specification states (http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html):

    Linked list implementation of the List interface. Implements all optional list operations, and

    permits all elements (including null). In addition to implementing the List interface, the LinkedListclass provides uniformly named methods to get, remove and insert an element at the beginning andend of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue.

    The class implements the Deque interface, providing first-in-first-out queue operations for add,poll, along with other stack and deque operations.

    All of the operations perform as could be expected for a doubly-linked list. Operations that indexinto the list will traverse the list from the beginning or the end, whichever is closer to the specifiedindex.

    Classjava.util.LinkedList implements the java.util.Dequeinterface. Hence, it canbe used as a stack, but the application programmer who uses it will need to stick to the stack-only methods in this class, i.e. addFirst,removeFirstand peekFirst.

    Class java.util.LinkedListis in the JCF since Java 1.2, but it has been retrofitted to im-plement theDequeinterface in Java 1.6.

    SHS Wong Seehttp://vle.aston.ac.uk/for more learning materials 13/14

  • 8/9/2019 USING STACKS

    14/14

    6. 101 CLASSJAVA.UTIL.LINKEDLIST CS2310 DSAJ 2014/2015

    Learning Outcomes

    You should now be able to:

    -apply stack data structures appropriately to solve software

    problems

    -explain why java.util.Stack in JCF is not a pure implementation

    of the stack ADT

    -appreciate how usage of a stack is largely independent of how the

    stack ADT is implemented

    If not, go through the notes again, read the textbook and/or

    consult the module tutor regarding queries on any of the learning

    materials.

    SHS Wong See http://vle aston ac uk/ for more learning materials 14/14