Stack ADT. B/W Confirming Pages

Size: px
Start display at page:

Download "Stack ADT. B/W Confirming Pages"

Transcription

1 wu23399_ch19.qxd 1/2/07 20:46 Page Stack ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the Stack ADT. Develop applications using stacks. Implement the Stack ADT by using an array. Implement the Stack ADT by using a linked list. the key differences between the array Explain and linked implementations of the Stack ADT. 1035

2 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT I n t r o d u c t i o n We continue our study of ADTs with the Stack ADT in this chapter. As we did in Chapter 18, we start with the definition of the Stack ADT and present two different implementations. We conclude the chapter with sample applications of the Stack ADT. The Stack ADT is modeled after a physical stack of items, such as a stack of pancakes or a stack of plates. If you were asked to remove any plate from a stack of plates, which one would you remove? The topmost one, of course. Similarly, the most effortless place to add a new plate is at the top of the stack. Like its physical counterpart, the defining feature of the Stack ADT is its restrictive insertion and removal operations. An item can only be added to the top of the stack, and only the topmost item of the stack can be removed. Because of this restriction, the Stack ADT is quite simple. And consequently, its implementations are relatively straightforward, compared to the List ADT. As simple as it may be, the Stack ADT is remarkably versatile and useful in many diverse types of applications. stack top of stack LIFO 19.1 The Stack ADT A stack is a linearly ordered collection of elements where elements, or items, are added to and removed from the collection at the one end called the top of stack. This restriction will ensure that the last element added to a stack is the first to be removed next. For this reason, a stack is characterized as a last-in, first-out (LIFO) list. Figure 19.1 shows a sample generic stack named samplestack with five elements and another stack named with five three-letter animal names. Items in a stack are said to be linearly ordered because the order in which the items are added and removed follows the strict linear sequence. In other words, the item at the ith position below the top of the stack moves to the (i 1)st position when the topmost item is removed. Similarly, the item at the ith position below the top of the stack moves to the (i 1)st position when a new item is added to the top of the stack. TOP E 4 E 3 This is the top of stack. New element is added here, and only the top-of-stack element can be removed. TOP "bee" "dog" E 2 "ape" samplestack E 1 "gnu" E 0 "cat" Figure 19.1 A generic stack samplestack with five elements and a stack with three-letter animal names.

3 wu23399_ch19.qxd 1/2/07 20:46 Page The Stack ADT 1037 push pop peek clear size isempty Because the addition and removal operations are restricted, the methods defined for the Stack ADT are much simpler than those defined for the List ADT. The add operation named push adds a new item to the top of the stack. The remove operation named pop removes the topmost item. The get operation named peek returns the topmost item, without actually removing it. There are two query operations named size and isempty. The size method returns the number of items in the stack, and the isempty method returns true if the size of the stack is 0. The update operation named clear empties the stack. The push operation will add the designated element to the top of the stack. The current elements in the stack are pushed down one position. The stack does not have any size restriction. It will grow without bound. Of course, the computer memory is not limitless, so there will be a hardware limitation on how big a stack can grow, but there will be no size restriction at theadt level.also, there is no restriction on the elements. You can add duplicates, for instance. Figure 19.2 illustrates the push operation. The pop operation is the reverse of the push operation. It will remove the topmost element from the stack if there is any. If the stack is empty, then the operation will throw an exception. There are a number of possible Java exceptions that the operation can throw, and we will discuss them in Section For now, we ll just say that the operation will throw some kind of exception. Figure 19.3 illustrates the pop operation on nonempty and empty stacks. The peek operation is just like the pop operation except that the top element is not removed from the stack. Figure 19.4 illustrates the peek operation on nonempty and empty stacks. The clear operation removes all elements in the stack. It causes no problem to call the clear operation on an empty stack. This operation becomes handy, for example, when you want to clear the stack before reusing it for processing the next batch of input data. See Figures 19.5 and The size operation returns the number of elements in the stack. This operation is not as commonly used on the stacks as the isempty operation, but we will include it in the specification as it is not costly to implement this operation. Including this operation maintains the consistent set of methods available on all types of collection objects. The isempty operation tests whether the stack is empty. If it is, then true is returned. Otherwise, false is returned. See Figure Before After TOP "bat" TOP "dog" push("bat") "dog" "ape" "ape" "cat" "cat" Figure 19.2 A sample push operation on the stack.

4 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT Before After TOP "bat" "dog" pop( ) TOP "dog" "ape" "cat" returns "ape" "cat" "bat" pop( ) throws <exception> Figure 19.3 Sample pop operations on the stack. Before After TOP "dog" peek( ) TOP "dog" "ape" "cat" returns "ape" "cat" "dog" No structural change is made. peek( ) throws <exception> Figure 19.4 Sample peek operations on the stack.

5 wu23399_ch19.qxd 1/2/07 20:46 Page The Stack ADT 1039 Before After TOP "dog" "ape" clear( ) "cat" Figure 19.5 A sample clear operation on the stack. Before After TOP "dog" TOP "dog" "ape" size( ) "ape" "cat" returns "cat" 3 No structural change is made. Figure 19.6 A sample clear operation on the stack. Before After TOP "dog" isempty( ) TOP "dog" "ape" "cat" returns "ape" "cat" false isempty( ) returns Figure 19.7 true Sample isempty operations on the stack.

6 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 1. Draw the stack after executing the following operations, starting with an empty stack called. String bee = new String("bee"); String cat = new String("cat");.clear( );.push(bee);.push(cat);.pop( ); 2. Repeat Question 1 with the following statements: String bee = new String("bee"); String cat = new String("cat"); String dog = new String("dog"); petstack.push(bee); petstack.push(cat); petstack.push(dog); petstack.peek( ); petstack.pop( ); petstack.pop( ); petstack.push(dog); 19.2 The Stack Interface As we did for the List ADT, we will use a Java interface to define the Stack ADT. We will continue to prefix our interfaces and classes with NPS. (There are no conflicts because no interface named Stack and no classes named ArrayStack and LinkedStack exist in the java.util packages; but for consistency, we will prefix all of our interfaces and classes with NPS.) Formalizing what we have presented in Section 19.1, we have the following definition: NPSStack package edu.nps.util; public interface NPSStack<E> { public void clear( ); public boolean isempty( ); public E peek( ) throws NPSStackEmptyException; public E pop( ) throws NPSStackEmptyException; public void push(e element); public int size( );

7 wu23399_ch19.qxd 1/2/07 20:46 Page The Stack Interface 1041 TABLE 19.1 The NPSStack interface Table Interface: NPSStack void clear( ) Removes all elements from the stack. boolean isempty( ) Determines whether the stack is empty. Returns true if it is empty; false otherwise. Object peek( ) throws NPSStackEmptyException Returns the top-of-stack element without removing it from the stack. Throws an exception when the stack is empty. Object pop( ) throws NPSStackEmptyException Removes the top-of-stack element and returns it. Throws an exception when the stack is empty. void push( Object element ) Adds an element to the stack. This element becomes the new top-of-stack element. int size( ) Returns the number of elements in the stack. Table 19.1 summarizes the methods of the NPSStack interface. The peek and pop methods are defined to throw an NPSStackEmptyException. We could have thrown an NPSNoSuchElementException because there is no such (top-of-stack) element when you attempt to pop or peek an empty stack. However, NPSNoSuchElementException is equally applicable, for example, when you search for an element that is not in a data structure. It is preferable to use an exception that identifies the error condition as precisely as possible, instead of using a generic exception. Because the specific error condition that would result in an exception for the pop and peek operations is an empty stack, we chose to throw an exception specifically defined for this purpose. The NPSNoSuchElementException class is a very simple class. Here s the definition: NPSNoSuchElementException package edu.nps.util; public class NPSStackEmptyException extends RuntimeException { public NPSStackEmptyException( ) { this("stack is empty"); public NPSStackEmptyException(String message) { super(message);

8 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.3 The Array Implementation In this section, we will implement the NPSStack interface by using an array to store the stack elements. Figure 19.8 illustrates the array implementation of the Stack ADT. The NPSArrayStack Definition The NPSArrayStack class implements the NPSStack interface, and its class declaration is as follows: package edu.nps.util; public class NPSArrayStack<E> implements NPSStack<E> { //class body comes here We use an array element to store the stack elements and an int variable count to keep track of the number of elements currently in the stack. Since the Java array uses zero-based indexing, the value of count is also the index of the array where we add the next element. We will also define a constant for the default size we use when creating the array in the zero-argument constructor. These data members are declared as private static final int DEFAULT_SIZE = 25; private E[ ] element; private int count; ADT Stack Array Implementation TOP "bat" "dog" "ape" "cat" This value is also the index of the array where we add the next item. :NPSArrayStack count 4 element n :String "bat" :String "dog" :String "ape" :String The array is drawn vertically to capture the nature of stack more clearly. "cat" Figure 19.8 An array implementation of the Stack ADT.

9 wu23399_ch19.qxd 1/2/07 20:46 Page The Array Implementation 1043 We will define two constructors: one takes no argument and another takes one argument that specifies the initial size of the array. They are defined as follows: public NPSArrayStack( ) { this(default_size); public NPSArrayStack(int size) { if (size <= 0) { throw new IllegalArgumentException( "Initial capacity must be positive"); element = (E[]) new Object[size]; count = 0; clear Notice that we first create an array of Object and then typecast it to an array of E, the type parameter. This is necessary because it is not allowed to create an array of generic type in Java. We will set element[i] to null, where i = 0,..., count-1, so the objects referenced by element[i] will be garbage-collected. We will then reset the count variable to 0. public void clear( ) { for (int i = 0; i < count; i++) { element[i] = null; count = 0; isempty This operation is straightforward. If the value of count is 0, then the stack is empty. Otherwise, the stack is not empty. public boolean isempty( ) { return (count == 0); peek This is one of the two operations that can potentially throw an NPSStackEmpty- Exception. We throw an NPSStackEmptyException when the stack is empty. Otherwise, we return the top-of-stack element. public E peek() throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { Be careful! The current top return element[count-1]; of stack is at the (count-1) index position.

10 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT pop push The pop operation removes the top-of-stack element. If the stack is not empty, we adjust the count data member and remove the topmost element by setting the value of the corresponding index position to null. Here s the method: public E pop() throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { count--; E item = element[count]; element[count] = null; return item; Adding a new item to the top of a stack and updating the count data member can be expressed easily and concisely as element[count] = item; count++; Can be combined into one statement as element[count++] = item; The complication will arise when the array is fully occupied. When the array is full, we need to enlarge it to accommodate more items. We will define a private method called expand to create a new array that is 1.5 times larger than the current array. This is the same technique we used in the NPSArrayList class. Here s the method: private void expand( ) { // create a new array whose size is 150% of // the current array int newlength = (int) (1.5 * element.length); E[] temp = (E[]) new Object[newLength]; // now copy the data to the new array for (int i = 0; i < element.length; i++) { temp[i] = element[i]; element = temp; The push method is defined as follows: public void push(e item) { if (count == element.length) { expand( ); element[count++] = item;

11 wu23399_ch19.qxd 1/2/07 20:46 Page The Array Implementation 1045 size The last method is straightforward. We simply return the value of the count data member. public int size ( ) { return count; Here s the complete source code (for brevity, javadoc and most other comments in the actual source file are removed here): NPSArrayStack package edu.nps.util; public class NPSArrayStack<E> implements NPSStack<E> { private static final int DEFAULT_SIZE = 25; private E[ ] element; private int count; public NPSArrayStack( ) { this(default_size); Constructor public NPSArrayStack(int size) { if (size <= 0) { throw new IllegalArgumentException( "Initial capacity must be positive"); element = (E[]) new Object[size]; count = 0; public void clear() { clear for(int i = 0; i < count; i++) { element[i] = null; count = 0; public boolean isempty() { isempty return count == 0; public E peek( ) throws NPSStackEmptyException { if (isempty( )) { peek

12 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT throw new NPSStackEmptyException( ); else { return element[count-1]; public E pop() throws NPSStackEmptyException { pop if (isempty( )) { throw new NPSStackEmptyException( ); else { count--; E item = element[count]; element[count] = null; return item; public void push(e item) { push if (count == element.length) { expand( ); element[count++] = item; public int size( ) { size return count; private void expand( ) { expand int newlength = (int) (1.5 * element.length); E[] temp = (E[]) new Object[newLength]; for (int i = 0; i < element.length; i++) { temp[i] = element[i]; element = temp;

13 wu23399_ch19.qxd 1/2/07 20:46 Page The Linked-List Implementation Draw the array stack (like the right-hand side diagram in Figure 19.8) after executing the following operations, starting with an empty stack called. String bee = new String("bee"); String cat = new String("cat");.clear();.push(cat);.push(bee); 2. What is the purpose of the enlarge method? 3. What will happen if you replace the statement inside the else block of the pop method with the following? return element[count--]; 19.4 The Linked-List Implementation The linked-list implementation of the Stack ADT follows the same implementation pattern for the List ADT in Chapter 18. Figure 19.9 illustrates the linked-list implementation of the Stack ADT. ADT Stack Linked-List Implementation :String "bat" :NPSLinkedStack :String TOP "bat" "dog" "ape" "cat" count 4 topofstack "dog" :String "ape" The links are drawn pointing downward to capture the nature of stack more clearly. :String "cat" Figure 19.9 A linked-list implementation of the stack.

14 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT The StackNode Class The linked node structure for the stack is exactly the same as the one for the list. The StackNode class is defined as the inner class of the NPSLinkedStack class. Here s the class definition: class StackNode { private E item; private StackNode next; public StackNode(E item) { this.item = item; this.next = null; The NPSLinkedStack Class We keep two data members in the class. The first data member is a reference variable topofstack that points to the top-of-stack element. We adjust its value every time we pop an item from or push an item onto the stack. The second data member is an int variable count that keeps track of the number of elements currently in the stack. Their declarations are as follows: private StackNode topofstack; Private int count; We define only a single constructor that takes no arguments and sets the stack to its initial state, which is an empty stack. The constructor is defined as follows: public NPSLinkedStack( ) { clear( ); clear When we reset the topofstack pointer to null, the topmost node will get garbagecollected (because no pointers point to it any more). When this topmost node gets garbage-collected, the node below no longer has a pointer pointing to it, which causes this node to be garbage-collected also. This ripple effect will eventually cause all nodes to be garbage-collected. Here s the clear method: public void clear( ) { topofstack = null; count = 0;

15 wu23399_ch19.qxd 1/2/07 20:46 Page The Linked-List Implementation 1049 isempty The isempty method is implemented easily by checking the value of the data member count: public boolean isempty( ) { return count == 0; peek If the stack is empty, we throw an NPSstackEmptyException. Otherwise, we return the top-of-stack node (without actually removing it). Here s the method: public E peek( ) throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { pop return topofstack.item; If the stack is empty, we throw an NPSStackEmptyException. Otherwise, we set a temp pointer to the topmost item, update the topofstack pointer, and return the topmost item. Here s the method: public E pop( ) throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); push else { count--; E temp = topofstack.item; topofstack = topofstack.link; return temp; Adding a new element to a link-based stack is simpler than adding to an array-based stack because we do not have to worry about the overflow condition. All we need to do is to allocate a new node, adjust the topofstack pointer, and increment the counter. The method is defined as follows: public void push(e element) { StackNode newtop = new StackNode(element); newtop.link = topofstack; //add the new node to top topofstack = newtop; //set new node as top-of-stack count++;

16 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT size The size method simply return the value of the data member count: public int size( ) { return count; We are now ready to list the complete NPSLinkedStack class. In the source code listing, we do not show any javadoc comments, to keep the listing to a manageable size. The actual source code includes the full javadoc comments. NPSLinkedStack package edu.nps.util; public class NPSLinkedStack<E> implements NPSStack<E> { private StackNode topofstack; private int count; public NPSLinkedStack( ) { clear( ); public void clear( ) { topofstack = null; count = 0; public boolean isempty( ) { return (count == 0); public E peek( ) throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { return topofstack.item; public E pop( ) throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { count--; E temp = topofstack.item; Constructor clear isempty peek pop

17 wu23399_ch19.qxd 1/2/07 20:46 Page The Linked-List Implementation 1051 topofstack = topofstack.link; return temp; public void push(e element) { StackNode newtop = new StackNode(element); newtop.link = topofstack; topofstack = newtop; count++; public int size( ) { return count; class StackNode { private E item; private StackNode link; //points to the element //one position below this node public StackNode(E item) { this.item = item; this.link = null; push size StackNode 1. Draw the linked stack (like the right-hand side diagram in Figure 19.9) after executing the following operations, starting with an empty stack called. String bee = new String("bee"); String cat = new String("cat");.clear();.push(cat);.push(bee); 2. Instead of using count == 0 to check for an empty stack, can we use topofstack == null?

18 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.5 Implementation Using NPSList At the beginning of this chapter, we wrote that a stack can be characterized as a special kind of a list called a LIFO list. A stack is a LIFO list because the last item to be added to a stack is the first item to be removed from the stack next. We can in fact implement the Stack ADT by using a list. Consider the following NPSListStack class: NPSListStack package edu.nps.util; public class NPSListStack<E> implements NPSStack<E> { private static final int FRONT = 0; private NPSList<E> list; public NPSListStack( ) { list = new NPSLinkedList<E>(); public void clear( ) { list.clear(); public boolean isempty( ) { return list.isempty(); public E peek( ) throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { return list.get(front); public E pop( ) throws NPSStackEmptyException { if (isempty( )) { throw new NPSStackEmptyException( ); else { return list.remove(front); public void push(e element) { list.add(front, element);

19 wu23399_ch19.qxd 1/2/07 20:46 Page Sample Application 1053 public int size( ) { return list.size(); See how easily and succinctly the whole class can be implemented. Notice that in this implementation, we treat the first item in the linked list as the top-of-stack item. Do you know why? Instead of the NPSLinkedList class, we can use the NPSArrayList class. But with the NPSArrayList class, we should treat the last item in the list as the top-of-stack element to avoid the shifting of items when a new item is added Sample Application Application Matching HTML Tags The use of the Stack ADT is quite common in many different applications. In this section we will illustrate a typical use of a stack.we will write a program that checks the correctness of a given HTML document. An HTML, which stands for Hyper Text Markup Language, is a markup language designed for creating a web page. HTML uses a set of predefined tags to describe the structure of a document.the tags are used, for example, to specify the title, different levels of headings, numbered lists, and tables in a document. XML, or extended Markup Language, is another markup language that is used widely in today s computing world. It is not necessary to understand HTML fully to appreciate the use of a stack in checking the syntax of an HTML document.we only need to know how the HTML tags are organized in a document.the following is a very small (and valid) HTML document: <html> <head> <title>a sample HTML page</title> </head> <body> <h1>sample HTML</h1> <p>see how the tags are matched in pairs?</p> <h4>this is a table</h4> <table border="2"> <tr> <td>row 1 column 1</td> <td>row 1 column 2</td> </tr> </table> </body> </html>

20 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.6 Sample Application continued Figure A Web browser displaying the sample HTML document. Figure shows how this HTML document is displayed in a Web browser. The Web browser interprets the tags in the given HTML document and renders the page accordingly. The key characteristic of HTML tags is that the tags come in pairs: the opening and matching closing tags. There s an exception to this rule, but we will ignore it for the sake of simplicity in the following discussion (see Exercise 11). For example, the opening tag for the title is <title> and its matching closing tag is </title> The closing tag includes the forward slash (/) before the tag name. The tag names are caseinsensitive, so it doesn t matter, for example, if we specify the opening tag for the title as or as <title> <TITLE> The tags in the example HTML document are displayed in blue for easy viewing. The text in black is the content that gets displayed in the Web browser. If we strip the content,

21 wu23399_ch19.qxd 1/2/07 20:46 Page Sample Application 1055 this is what we get (tags are indented to show the structure clearly): <html> <head> <title> </title> </head> <body> <h1> </h1> <p> </p> <h4> </h4> <table border= 2 > <tr> <td> </td> <td> </td> </tr> </table> </body> </html> Notice how the matching tags are nested. We will never encounter a situation in which the matching tags cross over. In other words,in a valid HTML document,we will never face a situation like this: Invalid <body> <table> </body> </table> This type of cross over will not happen in a valid HTML file. We can characterize the formulation of tags in a valid HTML document as follows: 1. All opening tags have matching closing tags. 2. When a closing tag is encountered in the document, its corresponding opening tag was already encountered.that is, opening tags always come before the closing tags. 3. Tags can be nested, but they never overlap.

22 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.6 Sample Application continued These characteristics call for a stack to check the validity of a given HTML document. Here s the pseudocode for the syntax checker: NPSStack tagstack = new NPSArrayStack( ); boolean haserror = false, done = false; while (!done) { If all tags are processed and yet the stack is not empty, then it means there were opening tags with no matching closing tags. if (no more tags in a file) { done = true; if (!tagstack.isempty( )) { haserror = true; else { nexttag = get next tag from the file; if (nexttag is an opening tag) { tagstack.push(nexttag); //every opening tag gets //stacked exactly once else { //it's a closing tag If the next incoming tag is a closing tag, its corresponding opening tag must be the current top-of-stack element because of the properly nested characteristic. toptag = tagstack.pop( ); if (toptag does not match nexttag) { done = true; haserror = true; if (haserror) { //Invalid HTML else { //Valid HTML To concentrate on the stack processing, we assume the two helper classes HTML TagRetriever and HTMLTag. An HTMLTagRetriever object handles the retrieval of HTML tags from the specified file. An HTMLTag object represents a single HTML tag. Implementation of these classes is left as an exercise. Table 19.2 lists the methods of HTMLTagRetriever, and Table 19.3 lists the method of HTMLTag. Now we are ready to implement the pseudocode. Let s define a class named HTML TagChecker. The major portion of the logic expressed in the pseudocode is implemented in the key method called isvalid. This method returns true if the tags in the designated

23 wu23399_ch19.qxd 1/2/07 20:46 Page Sample Application 1057 Table 19.2 The HTMLTagRetriever class Table Class: HTMLTagRetriever HTMLTagRetriever( String filename ) throws IOException Constructs a new HTMLTagRetriever object and associates it to the file with the name filename. Throws an IOException if the said file cannot be opened. void reset( ) Resets this object so the processing of the tags can be repeated from the beginning. void reset( String filename ) throws IOException Same as the reset method with no parameter. This method, however, associates the object to the new file.throws an IOException if said file cannot be opened. boolean hasmoretags( ) Returns true if there are more tags in the file. Otherwise, returns false. HTMLTag nexttag( ) throws NoSuchElementException Returns the next HTMLTag object in the file. If there are no more tags, then the NoSuchElementException exception is thrown. file are syntactically correct. Otherwise, it returns false. The name of the file to process is passed to the constructor of HTMLTagChecker. Here s the class: HTMLTagChecker import edu.nps.util.*; import java.io.ioexception; public class HTMLTagChecker { private NPSStack<HTMLTag> tagstack; private HTMLTagRetriever tagretriever; public HTMLTagChecker(String filename) throws IOException { tagstack = new NPSArrayStack<HTMLTag>( ); tagretriever = new HTMLTagRetriever(filename);

24 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.6 Sample Application continued Table 19.3 The HTMLTag class Table Class: HTMLTag HTMLTag(String text) Creates a new HTMLTag object.the parameter text is the actual string, such as <body> and <title>,for the tag. boolean match(htmltag tag) Compares the parameter tag with this HTMLTag object in a caseinsensitive manner.the tag object can represent either the opening or the closing tag.the method will make the appropriate checking. Forexample, if this HTMLTag object represents <HEAD> and the argument tag object represents </HEAD>, then it is a match. Likewise, if this HTMLTag object represents </HEAD> and the argument tag object represents <HEAD>, then it is a match also. If there is a match, the method returns true. Otherwise, it returns false.the opening HTMLTag object can contain attribute values. For example, in the tag <TABLE border="2"> the border attribute specifies the width of the table border.this method correctly matches the opening tag that includes attributes with its closing tag. boolean isopeningtag( ) Returns true if this object represents an opening tag. Otherwise, returns false. boolean isclosingtag( ) Returns true if this object represents a closing tag. Otherwise, returns false. public boolean isvalid( ) { HTMLTag nexttag = null, toptag = null; tagstack.clear( ); boolean haserror = false, done = false; while (!done) { if (!tagretriever.hasmoretags( )) { //no more tags done = true;

25 wu23399_ch19.qxd 1/2/07 20:46 Page Sample Application 1059 if (!tagstack.isempty( )) { //there are some //leftover opening tags haserror = true; //with no matching closing tags done = true; else { nexttag = tagretriever.nexttag( ); if (nexttag.isopeningtag( )) { tagstack.push(nexttag); else { //it's a closing tag toptag = tagstack.pop( ); if (!toptag.match(nexttag)) { done = true; haserror = true; return haserror; /// M A I N m e t h o d // public static void main(string[] arg) { try { HTMLTagChecker checker = new HTMLTagChecker("index.html"); if (checker.isvalid()) { System.out.println("Input HTML file is valid"); else { System.out.println("Input HTML file is NOT valid"); catch (IOException e) { System.out.println("Error opening the designated file");

26 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.7 Sample Application Development backtracking Solving a Maze with Backtracking Many computer problems can be solved by the technique called backtracking. The name characterizes how the solution to a problem is found. Consider a maze problem. We define a maze to be a two-dimensional array of cells.each cell has four sides with at most three sides having a wall. You can move from one cell to an adjacent cell if there is no wall between the two cells. Two special cells are indentified as the entry and exit cells. The problem is to find a path that takes you from the entry cell to the exit cell of a given maze.figure shows a sample 5-by-5 maze. For humans, finding a solution path for a such small maze is almost immediate. But when the maze gets larger, say, 100 by100, finding a solution is not an easy matter anymore.(we re talking here about a human finding a solution for a maze drawn on a sheet of paper,and not about finding solution for a real-life maze or labyrinth.) What kind of a computer solution can we devise to find a solution path? We assume here that a given maze includes at least one solution path. A maze is represented by a Maze object that consists of N-by-M cells. A cell is represented by a MazeCell object. The Maze and MazeCell classes are described in Tables 19.4 and 19.5, respectively. It is left as an exercise to implement these two classes. One brute-force solution is to visit cells randomly, starting from the entry cell. This is akin to a human walking blindly around the maze. This simplistic approach can be expressed in the following manner: public void solverandom(maze maze) { MazeCell current = maze.getentrycell(); MazeCell exit = maze.getexitcell(); Cell is identified by the row and column numbers. This cell, for example, is (2,0) S 4 E Solution Path (0,3) (0,2) (1,2) (2,2) (3,2) (1,3) (3,0) (4,0) (4,1) (4,2) (4,3) (3,3) (3,4) (2,4) S E Figure A sample maze with 5-by-5 cells.the entry cell is marked with S and the exit cell with E. The dotted line shows the solution path from S to E. For this maze, there s exactly one solution path.

27 wu23399_ch19.qxd 1/2/07 20:46 Page Sample Development 1061 Table 19.4 The Maze class Table Class: Maze Maze( int rowsize, int columnsize ) Creates a new rowsize-by-columnsize maze. In its initial state, all cells are marked unvisited. One cell is designated as the entry cell and another cell as the exit cell. The entry and exit cells border one of the outer boundaries. void clear( ) Resets the maze to its initial state. int getcolumncount( ) Returns the number of columns of this maze. int getrowcount( ) Returns the number of rows of this maze. MazeCell getentrycell( ) Returns the entry cell. MazeCell getexitcell( ) Returns the exit cell. MazeCell getnextcell( MazeCell currentcell ) Returns a visitable cell adjacent to currentcell.returns null if there is no visitable adjacent cell. MazeCell getnextrandomcell( MazeCell currentcell ) Randomly selects and returns a cell adjacent to currentcell.the state of cell (visitable or not) is ignored by this method. while (current!= exit) { //move to a random adjacent cell current = maze.getnextrandomcell(current); System.out.println("Solution Path Found"); Since the method does not keep track of the cells visited, all it does is to output the message Solution Path Found when the exit cell is reached. It does not (cannot) print out the solution path. A much more elegant solution would be backtracking. Here s how it works. Mark the entry cell visited. Visit an adjacent cell that is not yet visited. Mark this cell visited (so we won t visit this cell again). Repeat this visit-and-mark-visited routine until either the exit cell is visited or there is no adjacent cell to visit from the current cell. If the exit cell is visited, then we found the solution. If there are no more adjacent cells to visit from the

28 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.7 Sample Application continued Table 19.5 The MazeCell class Table Class: MazeCell MazeCell( int rownum, int columnnum ) Creates a new cell. Each cell is identified by its row number and column number, the position it occupies in a maze. In its initial state, all four walls are up. int getcolumnnumber( ) Returns the column number of this cell. int getrownumber( ) Returns the row number of this cell. boolean isvisited( ) Returns true if the cell is not visited yet (i.e., it is visitable) and false if the cell is visited. boolean iswallup( int side ) Returns true if the wall of the specified side of this cell is up. Possible values for the parameter are MazeCell.NORTH, MazeCell.SOUTH, MazeCell.EAST, and MazeCell.WEST. void putwalldown( int side ) Knocks down the wall of the specified side of this cell. Possible values for the parameter are MazeCell.NORTH, MazeCell.SOUTH, MazeCell.EAST, and MazeCell.WEST. void setvisited( boolean state ) Sets the state of this cell.the value of true means the cell is visited and false means not visited. current node, we backtrack to the cell before the current cell and repeat the process again from that cell. Figure illustrates two backtracking steps. The key aspect of implementing this backtracking algorithm is to remember the cell to backtrack to.the ADT that goes hand in hand with backtracking is a stack.when we visit a cell, we push it onto a stack. The current cell is at the top of stack, and the adjacent cell we visit next from the current cell will be the new top of stack (and it will be the current cell in the next iteration). When we backtrack from a cell, we simply pop a stack. The new top of stack is the cell we re backtracking to. Figure shows the correspondence between the path and the stack content. We use the setvisited method of the MazeCell class to mark a visited cell. The getnextcell method of the Maze class returns a next visitable cell (a cell that is not yet

29 wu23399_ch19.qxd 1/2/07 20:46 Page Sample Development S 0 S 0 N S C backtrack from (2,0) to (1,0) C backtrack from (1,0) to (1,1) C A B C Figure This illustrates how the backtracking works.visited cells are marked with a red circle. Diagram A: There are no more adjacent cells to visit from the current cell (C), so we backtrack to cell (1,0). Diagram B: Again, there are no more adjacent from the current cell, so we backtrack. Diagram C: From the current cell, we can visit cell (0,1), so we visit it next (N). (2,1) S (2,2) 1 (1,2) C stack (0,2) (0,3) Figure The stack content shows the order of visiting cells in the path currently under consideration. visited) from a given cell. If there are no more visitable cells from a given cell, the method returns null. Here s the method that finds a solution path by backtracking: public void solvebacktracking(maze maze) { MazeCell current = maze.getentrycell(); MazeCell exit = maze.getexitcell(); NPSStack<MazeCell> stack = new NPSArrayStack<MazeCell>( ); stack.push(current); while (current!= exit) { current = maze.getnextcell(current);

30 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 19.7 Sample Application continued if (current!= null) { current.setvisited(true); //mark it visited stack.push(current); else { //no more visitable cells from the //top-of-stack cell, so backtrack current = stack.pop(); System.out.println("Solution Path:"); while (stack.isempty()) { //print out the solution System.out.println(stack.pop()); //path backward Because we are using a stack, the solution path found is printed backward from the exit cell to the entry cell.it is more natural to print out the path forward from the entry cell to the exit cell. This is left as an exercise. S u m m a r y Astack is a linearly ordered last-in, first-out (LIFO) collection of elements. An item can be added to only the top of a stack, and only the top item of a stack can be removed. An array and a linked-list are two possible implementations of the Stack ADT. The Stack ADT can be implemented easily by using a list (an instance of a class that implements the List ADT). Base implementation of the Stack ADT does not support any traversal operation. The use of the Stack ADT is illustrated in two sample applications: an HTML syntax checker and a maze solver. Backtracking is a technique used in finding a solution for a search problem. The Stack ADT is used in implementing the backtracking algorithm.

31 wu23399_ch19.qxd 1/2/07 20:46 Page 1065 Exercises 1065 K e y C o n c e p t s Stack ADT array implementation of Stack ADT linked-list implementation of Stack ADT backtracking E x e r c i s e s 1. Draw a state-of-memory diagram that shows the effect of the pop operation on a NPSLinkedStack. Use the state where there are four items in the stack before the pop operation. 2. Draw a state-of-memory diagram that shows the effect of the push operation on a NPSLinkedStack. Use the state where there are three items in the stack before the push operation. 3. Draw a state-of-memory diagram that shows the result of executing each of the following two sets of code. a. NPSStack stack = new NPSLinkedStack( ); Person p = new Person(...); stack.push(p); stack.push(p); b. NPSStack stack = new NPSLinkedStack( ); Person p1 = new Person(...); Person p2 = new Person(...); stack.push(p1); stack.push(p2); 4. Add a new method toarray to the NPSStack interface and implement the method in both NPSArrayStack and NPSLinkedStack. The toarray method will return an array with the bottommost element at position 0, element 1 above the bottom at position 1, and so forth. For a mathematically pure Stack ADT, we do not define such conversion operation. But in the actual use of stacks, we often need to access every element in the stack. For example, in the maze sample application, if the toarray method is available, we can easily print out the solution path in the forward direction (from the entry cell to the exit cell) instead of the backward direction that we printed in the solvebacktracking method. 5. Adding the toarray method is one way to provide access to all elements in a stack. Another way is to include the iterator method to the NPSStack interface that returns an iterator. Implement the iterator method in both NPSArrayStack and NPSLinkedStack. The iterator will access the items in the stack from top to bottom.

32 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT 6. Code a new implementation class for the Stack interface called NoDupStack that does not allow a duplicate of the existing element to be pushed onto the stack. We define an element e2 to be a duplicate of e1 if e1.equals(e2) is true. Define a new exception class called NPSDuplicateException and throw this exception from the push method when an attempt is made to push a duplicate. Use an array for this implementation. 7. Repeat Exercise 6, but this time use the linked nodes instead of an array. 8. In the NPSLinkStack class, the data member list is an instance of NPSLinkedList we use to maintain the stack elements. If a stack is a LIFO list (i.e., a stack IS-A a list), shouldn t we define it as a subclass of the NPSLinkedList class? Why is it wrong to so? 9. When implementing the NPSListStack class, we treat the first item in a list as the top-of-stack item. Modify the class so the last item in the linked list is treated as the top-of-stack item. Which implementation is more efficient? Why? 10. Implement the NPSListStack class using the NPSArrayList class. 11. Implement the HTMLTagRetriever class. There are some HTML tags that do not have the matching closing tags. For this exercise, assume such tags are <br>, <hr>, and <img> tags. The nexttag method must ignore these tags. 12. Implement the HTMLTag class. Pay close attention to the match method. Some opening tags, such as the <table> tag, can contain attributes in addition to the tag name. For example, the <table> tag can be or <table> <table border="2"> When you match the opening and closing tags, you have to ignore the attributes in the opening tags. 13. In this chapter, we assumed that a given maze has at least one solution path. Modify the solvebacktracking method so it will handle the case when a given maze does not have any solution. Terminate the method after displaying the message No Solution Path if there is no solution path. 14. The solvebacktracking method prints out the solution path backward. Modify the method so the solution path is printed forward from the entry cell to the exit cell. Assume the original definition of the NPSStack interface. Specifically, you cannot use the toarray method (see Exercise 4). Hint: Use another stack. 15. Implement the Maze and MazeCell classes. Their public methods are described in Tables 19.4 and 19.5, respectively. The most difficult aspect of this exercise is the creation of a maze, which is carried out in the constructor of the Maze class. Here s one way to create a maze that has exactly one solution path from the entry cell to the exit cell: 1. Start with all four walls up for every cell in the maze. 2. Knock down the walls to create paths.

33 wu23399_ch19.qxd 1/2/07 20:46 Page 1067 Exercises Randomly select the entry and exit cells. Make sure these are selected from the boundary cells (those that face the boundary of the maze). The basic idea of the algorithm for step 2 goes like this: Start from a random cell. Remember this cell in a list. Mark this cell as visited. (You will visit every cell in the maze exactly once.) Set this cell as current. Find an adjacent cell of the current cell that is not yet visited. Knock down the walls between this cell and the current cell. Set this cell as the current cell and repeat the process. If there are no more visitable cells from the current cell, remove a random cell from the list and repeat the process. Stop the routine when all cells in the maze are visited. Expressing this basic idea in a more formal pseudocode, we have the following: mark all cells as 'not visited'; currentcell = pick a random cell; list.add(currentcell); while (there are unvisited cells) { currentcell = list.get(random location); while (currentcell has a 'not visited' adjacent cell) { if (currentcell has more than 1 'not visited' adjacent cell) { list.add(currentcell); //put it back in the list //so other adjacent cells are //considered later previouscell = currentcell; currentcell = getnextcell(previouscell); mark currentcell as 'visited'; knock down the wall between previouscell and currentcell; list.add(currentcell); To support some of the operations expressed in the pseudocode, you may have to define additional methods in the MazeCell class. 16. Write a program that checks if the input arithmetic expression is syntactically correct. Assume the arithmetic expressions include only integer constants, four arithmetic operators, and parentheses. Nested parentheses are allowed. Here are examples of valid arithmetic expressions: * (2 + 7) (23 / (3-4)) / 8 12

34 wu23399_ch19.qxd 1/2/07 20:46 Page Chapter 19 Stack ADT And here are examples of invalid arithmetic expressions: * (4 + 2)) ) ( 17. Forth is a unique and interesting programming language. It can be characterized as a stack-oriented programming language where programs are written in postfix notation. If we write arithmetic expressions using postfix notation, we write them as <leftoperand> <rightoperand> <operator> For example, instead of writing we write in postfix notation. The ordinary way we write arithmetic expressions uses the notation called infix. Here are some examples that compare the infix and postfix expressions: Infix Postfix (8 5) * * 5 4 * (8 5) * Notice that postfix expressions do not include parentheses because they are not necessary. Write a program that evaluates a given postfix arithmetic expression that consists of integer constants and four arithmetic operators,, /, and *. You use a stack to remember the operands. Whenever you encounter an operand in the input postfix expression, stack it. When you encounter an operator in the input postfix expression, its left and right operands are in the stack. Pop the stack twice to get the left and right operands, compute the result, and push the result back to the stack. When there are no more operators left in the expression, the top-of-stack element in the stack is the result of the whole expression. You may assume the input postfix expression is syntactically correct, so you do not have to do any error checking.

List ADT. B/W Confirming Pages

List ADT. B/W Confirming Pages wu3399_ch8.qxd //7 :37 Page 98 8 List ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the List ADT. the List ADT using an array

More information

Queue ADT. B/W Confirming Pages

Queue ADT. B/W Confirming Pages wu23399_ch20.qxd 1/2/07 20:56 Page 1069 20 Queue ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the Queue ADT. Implement the Queue

More information

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S Stacks Stacks & Queues A linear sequence, or list, is an ordered collection of elements: S = (s 1, s 2,..., s n ) Stacks and queues are finite linear sequences. A Stack is a LIFO (Last In First Out) list.

More information

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack. STACK Stack ADT 2 A stack is an abstract data type based on the list data model All operations are performed at one end of the list called the top of the stack (TOS) LIFO (for last-in first-out) list is

More information

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011 CMPSCI 187: Programming With Data Structures Lecture 12: Implementing Stacks With Linked Lists 5 October 2011 Implementing Stacks With Linked Lists Overview: The LinkedStack Class from L&C The Fields and

More information

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified. The Stack ADT Stacks Set of objects in which the location an item is inserted and deleted is prespecified Stacks! Insert in order! Delete most recent item inserted! LIFO - last in, first out Stacks 2 The

More information

Assignment 5. Introduction

Assignment 5. Introduction Assignment 5 Introduction The objectives of this assignment are to exercise a few advanced object oriented programming and basic data structures concepts. The first mini-goal is to understand that objects

More information

Stack and Its Implementation

Stack and Its Implementation Stack and Its Implementation Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale tessema.mengistu@siu.edu Room - 3131 1 Definition of Stack Usage of Stack Outline

More information

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO) Outline stacks stack ADT method signatures array stack implementation linked stack implementation stack applications infix, prefix, and postfix expressions 1 Stacks stacks of dishes or trays in a cafeteria

More information

COMP 250 Winter stacks Feb. 2, 2016

COMP 250 Winter stacks Feb. 2, 2016 Stack ADT You are familiar with stacks in your everyday life. You can have a stack of books on a table. You can have a stack of plates on a shelf. In computer science, a stack is an abstract data type

More information

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 Chapter 7 s CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 The Abstract Data Type: Specifications of an abstract data type for a particular problem Can emerge during the design of the

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

Advanced Java Concepts Unit 3: Stacks and Queues

Advanced Java Concepts Unit 3: Stacks and Queues Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO).

More information

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3 UNIT 3 LINEAR DATA STRUCTURES 1. Define Data Structures Data Structures is defined as the way of organizing all data items that consider not only the elements stored but also stores the relationship between

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills

CSCI 136 Data Structures & Advanced Programming. Lecture 14 Fall 2018 Instructor: Bills CSCI 136 Data Structures & Advanced Programming Lecture 14 Fall 2018 Instructor: Bills Announcements Mid-Term Review Session Monday (10/15), 7:00-8:00 pm in TPL 203 No prepared remarks, so bring questions!

More information

Top of the Stack. Stack ADT

Top of the Stack. Stack ADT Module 3: Stack ADT Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Stack ADT Features (Logical View) A List that

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced

More information

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows: STACKS A stack is a linear data structure for collection of items, with the restriction that items can be added one at a time and can only be removed in the reverse order in which they were added. The

More information

Stacks Fall 2018 Margaret Reid-Miller

Stacks Fall 2018 Margaret Reid-Miller Stacks 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Today: Quiz 5 solutions Recursive add from last week (see SinglyLinkedListR.java) Stacks ADT (Queues on Thursday) ArrayStack

More information

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed stack method of expression evaluation in 1955. Topic 15 Implementing and Using "stack n. The set of things a person has to do in the future. "I haven't done it yet because every time I pop my stack something new gets pushed." If you are interrupted

More information

Lecture Data Structure Stack

Lecture Data Structure Stack Lecture Data Structure Stack 1.A stack :-is an abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real-world stack, for example a deck of cards

More information

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP

Stacks. Ordered list with property: Insertions and deletions always occur at the same end. INSERT DELETE A3 A3 TOP TOP TOP Stacks Ordered list with property: Insertions and deletions always occur at the same end. INSERT A3 A3 TOP DELETE A2 TOP A2 A2 TOP A1 A1 A1 A0 A0 A0 Stacks Implementation Implementation with arrays: Declare

More information

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 CMPSCI 187: Programming With Data Structures Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012 Implementing Stacks With Arrays The Idea of the Implementation Data Fields

More information

Project 1: Implementation of the Stack ADT and Its Application

Project 1: Implementation of the Stack ADT and Its Application Project 1: Implementation of the Stack ADT and Its Application Dr. Hasmik Gharibyan Deadlines: submit your files via handin by midnight (end of the day) on Thursday, 10/08/15. Late submission: submit your

More information

Stack Implementation

Stack Implementation Stack Implementation (In Java Using BlueJ) What is BlueJ? BlueJ is a Java integrated development environment (IDE) which has been designed specifically for learning object oriented programming in Java.

More information

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

CS 171: Introduction to Computer Science II. Stacks. Li Xiong CS 171: Introduction to Computer Science II Stacks Li Xiong Today Stacks operations and implementations Applications using stacks Application 1: Reverse a list of integers Application 2: Delimiter matching

More information

Stacks, Queues (cont d)

Stacks, Queues (cont d) Stacks, Queues (cont d) CSE 2011 Winter 2007 February 1, 2007 1 The Adapter Pattern Using methods of one class to implement methods of another class Example: using List to implement Stack and Queue 2 1

More information

CS 221 Review. Mason Vail

CS 221 Review. Mason Vail CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using

More information

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1) Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours TED (10)-3071 Reg. No.. (REVISION-2010) (Maximum marks: 100) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours PART

More information

Stacks. Revised based on textbook author s notes.

Stacks. Revised based on textbook author s notes. Stacks Revised based on textbook author s notes. Stacks A restricted access container that stores a linear collection. Very common for solving problems in computer science. Provides a last-in first-out

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)

More information

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5

Stack. 4. In Stack all Operations such as Insertion and Deletion are permitted at only one end. Size of the Stack 6. Maximum Value of Stack Top 5 What is Stack? Stack 1. Stack is LIFO Structure [ Last in First Out ] 2. Stack is Ordered List of Elements of Same Type. 3. Stack is Linear List 4. In Stack all Operations such as Insertion and Deletion

More information

[2:3] Linked Lists, Stacks, Queues

[2:3] Linked Lists, Stacks, Queues [2:3] Linked Lists, Stacks, Queues Helpful Knowledge CS308 Abstract data structures vs concrete data types CS250 Memory management (stack) Pointers CS230 Modular Arithmetic !!!!! There s a lot of slides,

More information

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider: Linear, time-ordered structures CS00: Stacks n Prichard Ch 7 n Data structures that reflect a temporal relationship order of removal based on order of insertion n We will consider: first come,first serve

More information

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework CHAPTER 3 & 4 Stacks & Queues The Collection Framework 1 Stack Abstract Data Type A stack is one of the most commonly used data structures in computer science A stack can be compared to a Pez dispenser

More information

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/2016 23:59 People in-charge: R. Mairon and Y. Twitto Introduction The objectives of this assignment are to exercise a few advanced object

More information

12 Abstract Data Types

12 Abstract Data Types 12 Abstract Data Types 12.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define the concept of an abstract data type (ADT). Define

More information

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does a problem require? What operations does a problem

More information

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ).

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ). Assignment 5 Introduction For this assignment, you will write classes to evaluate arithmetic expressions represented as text. For example, the string "1 2 ( * 4)" would evaluate to 15. This process will

More information

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017 Due: Wednesday, October 18, 11:59 pm Collaboration Policy: Level 1 Group Policy: Pair-Optional Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017 In this week s lab, you will write a program that can solve

More information

15-122: Principles of Imperative Computation, Fall 2015

15-122: Principles of Imperative Computation, Fall 2015 15-122 Programming 5 Page 1 of 10 15-122: Principles of Imperative Computation, Fall 2015 Homework 5 Programming: Clac Due: Thursday, October 15, 2015 by 22:00 In this assignment, you will implement a

More information

Data Structures G5029

Data Structures G5029 Data Structures G5029 Lecture 2 Kingsley Sage Room 5C16, Pevensey III khs20@sussex.ac.uk University of Sussex 2006 Lecture 2 Stacks The usual analogy is the stack of plates. A way of buffering a stream

More information

Lists. CITS2200 Data Structures and Algorithms. Topic 9

Lists. CITS2200 Data Structures and Algorithms. Topic 9 CITS2200 Data Structures and Algorithms Topic 9 Lists Why lists? List windows Specification Block representation Singly linked representation Performance comparisons Reading: Lambert and Osborne, Sections

More information

CE204 Data Structures and Algorithms Part 2

CE204 Data Structures and Algorithms Part 2 CE204 Data Structures and Algorithms Part 2 14/01/2018 CE204 Part 2 1 Abstract Data Types 1 An abstract data type is a type that may be specified completely without the use of any programming language.

More information

Stack Abstract Data Type

Stack Abstract Data Type 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 how Java implements a stack To learn how to implement a

More information

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions Lecture 4: Applications CS2504/CS4092 Algorithms and Linear Data Structures Dr Kieran T. Herley Department of Computer Science University College Cork Summary. Postfix notation for arithmetic expressions.

More information

infix expressions (review)

infix expressions (review) Outline infix, prefix, and postfix expressions queues queue interface queue applications queue implementation: array queue queue implementation: linked queue application of queues and stacks: data structure

More information

Stacks and Queues. Chapter Stacks

Stacks and Queues. Chapter Stacks Chapter 18 Stacks and Queues 18.1 Stacks The stack abstract data type allows access to only one element the one most recently added. This location is referred to as the top of the stack. Consider how a

More information

1. Stack Implementation Using 1D Array

1. Stack Implementation Using 1D Array Lecture 5 Stacks 1 Lecture Content 1. Stack Implementation Using 1D Array 2. Stack Implementation Using Singly Linked List 3. Applications of Stack 3.1 Infix and Postfix Arithmetic Expressions 3.2 Evaluate

More information

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions We normally write arithmetic expressions using infix notation: the operator (such as +) goes in between the

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant

More information

UNIT 3

UNIT 3 UNIT 3 Presentation Outline Sequence control with expressions Conditional Statements, Loops Exception Handling Subprogram definition and activation Simple and Recursive Subprogram Subprogram Environment

More information

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo The tree data structure 1 Trees COL 106 Amit Kumar Shweta Agrawal Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo 1 Trees The tree data structure 3 A rooted tree data structure stores

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked lists, allow insertion and deletion of elements

More information

Lab 7 1 Due Thu., 6 Apr. 2017

Lab 7 1 Due Thu., 6 Apr. 2017 Lab 7 1 Due Thu., 6 Apr. 2017 CMPSC 112 Introduction to Computer Science II (Spring 2017) Prof. John Wenskovitch http://cs.allegheny.edu/~jwenskovitch/teaching/cmpsc112 Lab 7 - Using Stacks to Create a

More information

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1 CSE 2100 Data Structures and Algorithms... In Java Stacks 1 What is Stack A stack is a collection of objects that are inserted and removed according to the last-in, first-out (LIFO) principle. Internet

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

LIFO : Last In First Out

LIFO : Last In First Out Introduction Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Stack is a data structure that is particularly useful in applications involving reversing.

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 11 Introduction to Computing II Wayne Snyder Department Boston University Today Object-Oriented Programming Concluded Stacks, Queues, and Priority Queues as Abstract Data Types Reference types: Basic

More information

CS350: Data Structures Stacks

CS350: Data Structures Stacks Stacks James Moscola Department of Engineering & Computer Science York College of Pennsylvania James Moscola Stacks Stacks are a very common data structure that can be used for a variety of data storage

More information

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 ) Unit - 2 By: Gurpreet Singh Dean Academics & H.O.D. (C.S.E. / I.T.) Yamuna Institute of Engineering & Technology, Gadholi What is a Stack? A stack is a

More information

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Collections Chapter 12 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Collections: Collection terminology The Java Collections API Abstract nature of collections

More information

Data Abstraction and Specification of ADTs

Data Abstraction and Specification of ADTs CITS2200 Data Structures and Algorithms Topic 4 Data Abstraction and Specification of ADTs Example The Reversal Problem and a non-adt solution Data abstraction Specifying ADTs Interfaces javadoc documentation

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Abstract Data Type Stack Version of February 2, 2013 Abstract These lecture notes are meant

More information

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms Introduction Problem Solving on Computer Data Structures (collection of data and relationships) Algorithms 1 Objective of Data Structures Two Goals: 1) Identify and develop useful high-level data types

More information

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016 Stacks Gaddis 18.1, 18.3 Molly A. O'Neil CS 2308 :: Spring 2016 The Stack ADT A stack is an abstract data type that stores a collection of elements of the same type The elements of a stack are accessed

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

CSIS 10B Lab 2 Bags and Stacks

CSIS 10B Lab 2 Bags and Stacks CSIS 10B Lab 2 Bags and Stacks Part A Bags and Inheritance In this part of the lab we will be exploring the use of the Bag ADT to manage quantities of data of a certain generic type (listed as T in the

More information

STACKS AND QUEUES. Problem Solving with Computers-II

STACKS AND QUEUES. Problem Solving with Computers-II STACKS AND QUEUES Problem Solving with Computers-II 2 Stacks container class available in the C++ STL Container class that uses the Last In First Out (LIFO) principle Methods i. push() ii. iii. iv. pop()

More information

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7 CPS109 Course Notes 7 Alexander Ferworn Unrelated Facts Worth Remembering The most successful people in any business are usually the most interesting. Don t confuse extensive documentation of a situation

More information

Linear Data Structure

Linear Data Structure Linear Data Structure Definition A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array Linked List Stacks Queues Operations on linear Data Structures Traversal

More information

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

CSCI 200 Lab 4 Evaluating infix arithmetic expressions CSCI 200 Lab 4 Evaluating infix arithmetic expressions Please work with your current pair partner on this lab. There will be new pairs for the next lab. Preliminaries In this lab you will use stacks and

More information

[CS302-Data Structures] Homework 2: Stacks

[CS302-Data Structures] Homework 2: Stacks [CS302-Data Structures] Homework 2: Stacks Instructor: Kostas Alexis Teaching Assistants: Shehryar Khattak, Mustafa Solmaz, Bishal Sainju Fall 2018 Semester Section 1. Stack ADT Overview wrt Provided Code

More information

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved Stacks Chapter 5 Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced Delimiters in an Infix Algebraic Expression A Problem Solved:

More information

Problem with Scanning an Infix Expression

Problem with Scanning an Infix Expression Operator Notation Consider the infix expression (X Y) + (W U), with parentheses added to make the evaluation order perfectly obvious. This is an arithmetic expression written in standard form, called infix

More information

Relationship between Pointers and Arrays

Relationship between Pointers and Arrays Relationship between Pointers and Arrays Arrays and pointers are intimately related in C and often may be used interchangeably. An array name can be thought of as a constant pointer. Pointers can be used

More information

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List. Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete

More information

CSCI 200 Lab 3 Using and implementing sets

CSCI 200 Lab 3 Using and implementing sets CSCI 200 Lab 3 Using and implementing sets In this lab, you will write a program that manages a set of workers, using the Worker hierarchy you developed in Lab 2. You will also implement your own version

More information

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures Stacks and Queues Gregory D. Weber CSCI C243 Data Structures Principal Points 1. The Stack interface: how to declare it, what it does. 2. Generics: why they were added to Java, how to use them. 3. The

More information

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \ BSc IT C Programming (2013-2017) Unit I Q1. What do you understand by type conversion? (2013) Q2. Why we need different data types? (2013) Q3 What is the output of the following (2013) main() Printf( %d,

More information

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Alice E. Fischer Lecture 6: Stacks 2018 Alice E. Fischer Data Structures L5, Stacks... 1/29 Lecture 6: Stacks 2018 1 / 29 Outline 1 Stacks C++ Template Class Functions 2

More information

CSC 1052 Algorithms & Data Structures II: Stacks

CSC 1052 Algorithms & Data Structures II: Stacks CSC 1052 Algorithms & Data Structures II: Stacks Professor Henry Carter Spring 2018 Recap Abstraction allows for information to be compartmentalized and simplifies modular use Interfaces are the Java construction

More information

Exceptions and Design

Exceptions and Design Exceptions and Exceptions and Table of contents 1 Error Handling Overview Exceptions RuntimeExceptions 2 Exceptions and Overview Exceptions RuntimeExceptions Exceptions Exceptions and Overview Exceptions

More information

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract Data Types Stack January 26, 2018 Cinda Heeren / Geoffrey Tien 1 Abstract data types and data structures An Abstract Data Type (ADT) is: A collection of data Describes what data are stored but

More information

Stacks and Queues. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

Stacks and Queues. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Stacks and Queues Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Two New ADTs Define two new abstract data types Both are restricted lists Can be implemented using arrays

More information

Student Performance Q&A:

Student Performance Q&A: Student Performance Q&A: 2016 AP Computer Science A Free-Response Questions The following comments on the 2016 free-response questions for AP Computer Science A were written by the Chief Reader, Elizabeth

More information

CSC 222: Computer Programming II. Spring 2005

CSC 222: Computer Programming II. Spring 2005 CSC 222: Computer Programming II Spring 2005 Stacks and recursion stack ADT push, pop, peek, empty, size ArrayList-based implementation, java.util.stack application: parenthesis/delimiter matching postfix

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

Lists are great, but. Stacks 2

Lists are great, but. Stacks 2 Stacks Lists are great, but Lists are simply collections of items Useful, but nice to have some meaning to attach to them Restrict operations to create useful data structures We want to have ADTs that

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 3- Stacks Some familiar stacks What is a stack? Add item on top of stack Remove item that is topmost Last In, First Out LIFO Specifications of the ADT Stack Specifications

More information

Linked Structures Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Linked Structures Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Linked Structures: Object references as links Linked vs. array-based structures Managing

More information

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard IV. Stacks 1 A. Introduction 1. Consider the problems on pp. 170-1 (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses checker () Calculate and display base-two

More information

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER

More information