14 Stacks, Queues, And Linked Lists

Save this PDF as:

Size: px
Start display at page:

Transcription

2 14-2 Java Au Naturel by William C. Jones 14-2 Another example where a queue would be important is in storing information about people who are waiting in line to buy tickets. Each new arrival goes to the rear of the queue (the enqueue operation), and the next ticket sold goes to the person who comes off the front of the queue (the dequeue operation). If you are selling movie tickets, an ordinary queue is appropriate. But if they are tickets to fly on an airline, a priority queue might be better: You would want to serve people whose plane will be taking off within the hour before people who have longer to wait, and you would want to serve first-class customers before customers buying the cheap tickets. Stock market application of stacks An investor buys and sells shares of stock in various companies listed in the stock market. What if the person sells 120 shares of a particular company for \$90 each at a time when the person owns 150 shares, of which 50 shares were bought in January at \$60 each, 50 more in February at \$70 each, and 50 more in March at \$80 each? Which of those particular shares are being sold? The federal tax laws require this investor to compute the profit and loss on a LIFO basis, i.e., the most recently purchased shares are sold first. So the profit on the sale is \$500 on the 50 purchased in March, \$1000 on the 50 purchased in February, and another \$600 (20 shares at \$30 each) on shares purchased in January. Therefore, an appropriate data structure for this situation is one stack of stock transactions for each of the companies that the person owns stock in. For this particular example of selling 120 shares, the software would remove from the top of the stack the first three transactions (the pop operation) and then add back the net transaction of 30 shares remaining at \$60 each (the push operation). Software to update the current stock holdings for the investor could be based on Transaction objects, each storing information about one stock transaction: company name, number of shares, price per share, and date of purchase. A text file could hold several lines of characters, each line giving the description of one transaction (a purchase of stock). The investor could start the program (which reads in the text file), enter several new buy-and-sell transactions, and then exit the program (which writes the updated information to a text file). A more detailed design is given in the accompanying design block. STRUCTURED NATURAL LANGUAGE DESIGN for stock transactions 1. Read the "transact.dat" file into an array of stacks, one stack per company. 2. Repeat as long as the user has more transactions to process... 2a. Get the next transaction from the user (buy or sell). 2b. Modify the information in the array of stacks accordingly. 3. Write the updated information to a file. The left side of Figure 3.1 shows a sequence of Push and Pop operations for a stack, starting from an empty stack. The right side of the figure shows a sequence of Enqueue and Dequeue operations for a queue, starting from an empty queue. Figure 14.1 Effect of method calls for stacks and queues

3 14-3 Java Au Naturel by William C. Jones 14-3 Some other applications of stacks You may need a program that reads in several lines of input, each containing what is supposed to be a properly-formed expression in algebra, and tells whether it is in fact legal. The expression could have several sets of grouping symbols of various kinds, ( ) and [ ] and {. Part of the parsing process is to make sure that these grouping symbols match up properly. The accompanying design block could be part of the logic for processing the algebraic expression. STRUCTURED NATURAL LANGUAGE DESIGN for grouping symbols 1. Get the next character on the input line; call it the currentchar. 2. If the currentchar is one of '(', '[', or '{', then... Push the currentchar on the stack. 3. Otherwise, if the currentchar is one of ')', ']', or '', then... 3a. If the stack is empty then... Conclude that this is not a properly-formed expression. 3b. Pop the top character from the stack. 3c. If that is not the other half of the currentchar, then... Conclude that this is not a properly-formed expression. 4. Otherwise [additional logic for other characters]... A Java compiler uses a stack to handle method calls, which works roughly as follows (very roughly), assuming calls is the stack of method calls and an Activation object keeps track of information for one method call: x = dostuff(y) causes calls.push (new Activation (arguments)); z = 3 for a local variable z causes calls.peektop().setvariable(z, 3); return 5 causes calls.pop(); x = 5. Stack and queue interfaces We will develop several different implementations of stacks and queues in this chapter. We specify what is common to all by defining interfaces. An interface describes what operations the object can perform but does not give the coding. So it describes an abstract data type. We call these two interfaces StackADT and QueueADT. They are shown in Listing 14.1 (see next page). Each has an operation to add an element to the data structure (push and enqueue), an operation to remove an element (pop and dequeue, which return the element removed), and two query methods: an operation to see what would be removed (peektop and peekfront), and an operation to tell whether the data structure has any elements to remove (isempty). We later develop coding for ArrayQueue, an implementation of QueueADT, and ArrayStack, an implementation of StackADT. As an example of how their methods can be used, the following is an independent method that reverses the order of the elements on a given stack, using a queue for temporary storage (independent simply means that the method works right no matter what class it is in). The coding removes each value from the stack and puts it on the queue, with what was on top of the stack going to the front of the queue. Then it removes each value from the queue and puts it on the stack. So the value that was originally on top of the stack ends up on the bottom of the stack: public static void reverse (StackADT stack) { QueueADT queue = new ArrayQueue(); while (! stack.isempty()) queue.enqueue (stack.pop()); while (! queue.isempty()) stack.push (queue.dequeue());

4 14-4 Java Au Naturel by William C. Jones 14-4 Listing 14.1 The StackADT and QueueADT interfaces public interface StackADT // not in the Sun library { /** Tell whether the stack has no more elements. */ public boolean isempty(); /** Return the value that pop would give, without modifying * the stack. Throw an Exception if the stack is empty. */ public Object peektop(); /** Remove and return the value that has been in the stack the * least time. Throw an Exception if the stack is empty. */ public Object pop(); /** Add the given value to the stack. */ public void push (Object ob); //############################################################## public interface QueueADT // not in the Sun library { /** Tell whether the queue has no more elements. */ public boolean isempty(); /** Return the value that dequeue would give without modifying * the queue. Throw an Exception if the queue is empty. */ public Object peekfront(); /** Remove and return the value that has been in the queue the * most time. Throw an Exception if the queue is empty. */ public Object dequeue(); /** Add the given value to the queue. */ public void enqueue (Object ob); The rest of the examples in this section are not used elsewhere in this book, so you could skip them. But even if your instructor does not assign them for study, you should at least skim through them to get a better feeling for the various problems that stacks and queues can help you solve.

5 14-5 Java Au Naturel by William C. Jones 14-5 The classic Tower of Hanoi problem You are given three stacks A, B, and C. Initially, B and C are empty, but A is not. Your job is to move the contents of A onto B without ever putting any object x on top of another object that was above x in the initial setup for A. Can you see how the following coding solves this problem, if it is called with n initially equal to A's size? public void shift (int n, StackADT A, StackADT B, StackADT C) { if (n == 1) B.push (A.pop()); else { shift (n - 1, A, C, B); // n-1 go from A onto C B.push (A.pop()); shift (n - 1, C, B, A); // n-1 go from C onto B Anagrams An interesting problem is to print out all the anagrams of a given word. That is, given an N-letter word with all letters different, print all the "words" you can form using each letter once, regardless of whether they are actual words in some language. The number of such rearrangements is N-factorial where N is the number of letters. The problem can be solved in several different ways, one of which uses one queue and one stack. We illustrate the process here and leave the coding as a major programming project. Say the word is abcdefgh and you have just printed ehcgfdba. The very next word in alphabetical order that you can form with those eight letters is ehdabcfg (compare the two to see why). The way one iteration of the main loop of the process goes from a stack containing ehcgfdba to that same stack containing ehdabcfg is as follows: Initially you have the letters on the stack in reverse order, and you have an empty queue: 1. Repeatedly pop a value from the stack and enqueue it on the queue, stopping as soon as you pop a value that comes alphabetically before the one you just enqueued. Call that value the "pivot". 2. Repeatedly dequeue a value and enqueue it, stopping as soon as you dequeue a value that comes alphabetically after the pivot. Push that value onto the stack. 3. Enqueue the pivot, then repeatedly dequeue a value and enqueue it, stopping as soon as you dequeue a value that is alphabetically before the pivot. Push it onto the stack. 4. Repeatedly dequeue a value from the queue and push it on the stack until the queue is empty. Evaluating postfix expressions Some calculators require you to enter arithmetic expressions in postfix notation. An arithmetic postfix expression is a sequence of numbers and operators + - * / % where each operator is placed directly after the two values it is to operate on. Some examples of postfix expressions and the corresponding expressions in the normal infix notation that you are used to are as follows: postfix notation infix notation (fully parenthesized) (7-2) * (3 + 4) * 5) * + (3 + (4 * 5)) / - ((3 + 7) - (8 / 2)) / - * + (3 + (4 * (2 - (6 / 3)))) The reverse notation, where the operator comes directly before the two values it is to operate on, is called prefix notation. It is used in the Scheme programming language.

6 14-6 Java Au Naturel by William C. Jones 14-6 Assume that an input string containing an arithmetic postfix expression has been read and separated into numbers and operators stored on a queue in order. The numbers are stored as Integer objects (with an intvalue method for getting the value) and the operators are stored as Character objects (with a charvalue method for getting the value). Then the accompanying design block is logic for evaluating the expression. The method in the upper part of Listing 14.2 (see next page) applies this algorithm. It throws an Exception if the data values in the queue do not form a legal postfix expression. STRUCTURED NATURAL LANGUAGE DESIGN for evaluating a postfix expression 1. Create a stack for storing numbers not yet combined with other numbers. 2. For each value you remove from the queue do... If it is a number then... Push it onto the stack. Otherwise, it is an operator, so... Pop the top two stack values and apply the operator to them. Push the result onto the stack. 3. Return the one remaining number on the stack. Converting infix notation to postfix notation Modern compilers usually process the normal infix expressions you write in your programs to produce the corresponding postfix expressions in the compiled code. That makes it much easier for the runtime system to evaluate the expressions. The full evaluation algorithm is far too complex to present here. But a method that does the job for the special case of a fully parenthesized numeric expression is not too hard. Assume that an input string containing a fully parenthesized normal infix expression has been read and separated into numbers and operators. They have been placed in a queue in the order they were read, stored as Integer objects and Character objects. Then a method for creating a new queue containing the corresponding postfix expression (suitable for input to the preceding method) is in the lower part of Listing It puts all operators on a stack (line 32) and pops them when the expression is complete (line 30). This independent method relies on two facts about postfix expressions: (1) Each operator must be moved to the point in the sequence where the right parenthesis that belongs to it occurs; (2) if several operators are "waiting" for their right parentheses, the next one to come along belongs to the most-recently-seen operator. You can verify these facts for the examples of postfix expressions shown earlier in this section. Note: A precondition for all exercises in this chapter is that all stack, queue, and list parameters of methods are non-null. Exercise 14.1 Write an independent method public static Object removesecond (StackADT stack): It removes and returns the element just below the top element if the stack has at least two elements, otherwise it simply returns null without modifying the stack. Exercise 14.2 Compute the values of these two postfix expressions. Also write these two postfix expressions in ordinary algebraic notation without evaluating any of the parts: (a) / (b) Exercise 14.3 (harder) Write an independent method public static void removedownto (StackADT stack, Object ob): It pops all values off the stack down to but not including the first element it sees that is equal to the second parameter. If none are equal, leave the stack empty. The ob parameter could be null. Exercise 14.4 (harder) Write an independent method public static Object removesecond (QueueADT queue): It removes and returns the element just below the top element. Precondition: The queue has at least two elements. Hint: Create a new object totally different from any that could possibly be on the queue.

8 14-8 Java Au Naturel by William C. Jones Implementing Stacks With Arrays Our ArrayStack implementation of StackADT stores values in a partially-filled array: We use an array itsitem of Objects and an int value itssize that tells how many elements the stack has. We store the elements in indexes 0 through itssize-1. The pop method tells the executor (i.e., the ArrayStack object carrying out the task) to decrement itssize and then return the value at index itssize. To push an element onto the stack, the executor puts the new element at index itssize and then increments itssize (just the opposite of pop). This logic is in Listing Removing an element or peeking at an element requires that there be an element in the data structure, so these methods first make sure that the stack is not empty. If it is empty, a runtime Exception is to be thrown. The obvious choice is an IllegalStateException (from java.lang). To throw the Exception, all you need do is execute the following statement. It immediately terminates execution of the method it is in: throw new IllegalStateException ("some explanatory message"); Listing 14.3 The ArrayStack class of objects public class ArrayStack implements StackADT { private Object[] itsitem = new Object [10]; private int itssize = 0; public boolean isempty() { return itssize == 0; public Object peektop() { if (isempty()) throw new IllegalStateException ("stack is empty"); return itsitem[itssize - 1]; public Object pop() { if (isempty()) throw new IllegalStateException ("stack is empty"); itssize--; return itsitem[itssize]; public void push (Object ob) { if (itssize == itsitem.length) { Object[] todiscard = itsitem; itsitem = new Object [2 * itssize]; for (int k = 0; k < itssize; k++) itsitem[k] = todiscard[k]; itsitem[itssize] = ob; itssize++;

9 14-9 Java Au Naturel by William C. Jones 14-9 When the ArrayStack object is first created, it starts with an array of size 10 (an arbitrary choice). Adding an element requires that there be room in the array. If not, you have to make the array bigger to hold the added element. Since you cannot simply add more components to an existing array, you create a new array that is twice as large and transfer the data to that other array. It becomes the new itsitem array. Figure 14.2 is the UML class diagram for the ArrayStack class. Figure 14.2 UML class diagram for the ArrayStack class The internal invariant of a class of objects is the condition that (a) each method ensures is true when the method exits, so that (b) each method can rely on it being true when the method starts execution, because (c) no outside method can change things so that the condition becomes false (due to encapsulation). The purpose of an internal invariant is to describe the relationship of the abstract concept to the state of the instance variables (and sometimes class variables). The ArrayStack class implements the abstract concept of a stack as follows: Internal invariant for ArrayStacks The int value itssize is the number of elements in the abstract stack. These elements are stored in the array of Objects itsitem at the components indexed 0 up to but not including itssize. If the stack is not empty, the top element of the stack is at index itssize-1. If k is any positive integer less than itssize, then the element at index k-1 is the element that will be on top of the stack immediately after popping off the element at index k. Linked-arrays implementation for faster execution This array implementation requires copying many data values when the array was not initially big enough. But it can waste space if the array was initially too big. There is a way to avoid both these problems of execution time and space usage, but it requires a little more programmer effort. Specifically, when the array fills up, make another array of equal size and put the additional data values there, without discarding the original array. Of course, you have to keep track of the "old" array somehow. Since an array is a kind of Object, and the new array has components for storing Objects, you can use one of those components in the new array to store a reference to the old array. For the ArrayStack push method in Listing 14.3, you could replace its if-statement by the following: if (itssize == itsitem.length - 1) { Object tosave = itsitem; itsitem = new Object [itssize + 1]; itsitem[itssize] = tosave; itssize = 0; You need a corresponding change in the pop method: When the current array is empty, check to see if there is another "older" array and, if so, go on to that one. You could simply replace the coding of Listing 14.3's pop method by the following coding:

10 14-10 Java Au Naturel by William C. Jones if (itssize == 0) { itssize = itsitem.length - 1; itsitem = (Object[]) itsitem[itssize]; itssize--; return itsitem[itssize]; Technical Note This coding throws a NullPointerException if there is no older array, since then itsitem becomes null. However, this is precisely what the specifications call for -- they do not require that an IllegalStateException be thrown, only that some RuntimeException be thrown. And this coding saves time as compared with an explicit test. But if you insist on throwing the "right" kind of Exception, use a try/catch statement to catch the "undesirable" one and then throw an IllegalStateException in its place. Efficiency The previous discussion brings up an important point: Efficiency is not a matter of execution time alone; it is a combination of space, time, and programmer effort. Coding that executes faster may be less efficient if it uses more space or requires more effort by the programmer and by any future maintainer of the program. You have to consider all three of these factors in determining the efficiency of an algorithm. There is a lot to be said for making efficiency the last consideration in developing software. Specifically, the first goal as you develop should be clarity of expression (make it easy to understand). The second goal should be correctness (avoid bugs). The third goal should be efficiency (make it fast or space-saving if the effort to do so is worth it). Putting clarity first simply means that you work on keeping the coding clear as you develop it, rather than writing sloppily and cleaning it up later. You will find it much easier to write correct and efficient coding if you strive for clarity from the beginning. Making your coding correct before you try for efficiency implies that you often choose the simplest way to get something done, as long as it works right. You may then come back to it and make it more efficient in terms of time and space (i.e., speed of execution or low use of RAM). One advantage is that you may then spot some bugs you missed the first time through. Moreover, it is well known that usually only about 10% of the coding is responsible for about 90% of the execution time, so you only have to work on a small part of the coding. This leaves the rest simple and straightforward, so that it will be easier to maintain in the future. Another advantage is that, if your boss forces you to deliver the product before you have finished it, it is better to deliver a correct but slow version than a fast but buggy version. Slowness will irritate customers, but some bugs can kill people in certain software (e.g., for medical or military purposes). In such cases, delivering buggy software is unethical. Exercise 14.9 How would the coding change in Listing 14.3 if you decided to have an instance variable itstop keep track of the index of the top element (using -1 when the stack is empty), instead of using itssize to keep track of the number of elements? Exercise (harder) Add a method public boolean equals (Object ob) to the ArrayStack class: The executor tells whether ob is an ArrayStack whose elements are equal to its own in the same order. Do not throw any Exceptions. Exercise 14.11* Add a method public int search (Object ob) to the ArrayStack class: The executor tells how many elements would have to be popped to have ob removed from the stack; it returns -1 if ob is not in the stack. Exercise 14.12* Write the isempty and peektop methods for the linked-arrays approach to implementing a stack described in this section, without changing itsitem.

11 14-11 Java Au Naturel by William C. Jones Implementing Queues With Arrays You could implement QueueADT the same way as Listing 14.3 except that elements are removed at the other end of the array from that on which elements are added. So you could code enqueue the same as push but code dequeue as follows: public Object dequeue() // in a simplistic implementation { if (isempty()) throw new IllegalStateException ("queue is empty"); Object valuetoreturn = itsitem[0]; for (int k = 1; k < itssize; k++) itsitem[k - 1] = itsitem[k]; itssize--; return valuetoreturn; Note that the for-statement copies the contents of itsitem[1] into the variable itsitem[0], then the contents of itsitem[2] into itsitem[1], etc. Copying in the opposite order would lose information. That is why the value to return is saved in a local variable before moving values down. Leave the coding of isempty unchanged. The coding of peekfront is the same as peektop except you return itsitem[0]. That completes the rather inefficient "movethem-all" implementation of QueueADT. A better implementation of queues The implementation of queues just described is very wasteful of execution time. If for instance the queue normally has around 100 elements in it, then each call of dequeue requires shifting 100 values around. A better way is to keep track of two places in the array, the index of the front of the queue and the index of the rear of the queue. Call these instance variables itsfront and itsrear. Forget about itssize. You add values at the rear and remove them at the front of the queue (except of course you cannot remove anything from an empty queue). So peekfront returns itsitem[itsfront]. The implementation of dequeue in this ArrayQueue class is as follows. Note that it corresponds line-for-line with ArrayStack's pop: public Object dequeue() // in ArrayQueue { if (isempty()) throw new IllegalStateException ("queue is empty"); itsfront++; return itsitem[itsfront - 1]; = Say itsfront is 10. Then if itsrear is 12, the queue has three values in it (at components 10, 11, and 12). If itsrear is 10, the queue has one value in it (at component 10). In general, the number of values in the queue is itsrear - itsfront + 1. So how do you tell when the queue is empty? When this expression has the value zero, namely, when itsrear is 1 less than itsfront. Since you should add the first element at index 0 for a newly created queue, itsfront should initially be 0, which means that itsrear must initially be -1 (1 less than itsfront because the queue is initially empty). This coding is in the upper part of Listing 14.4 (see next page).

12 14-12 Java Au Naturel by William C. Jones Listing 14.4 The ArrayQueue class of objects public class ArrayQueue implements QueueADT { private Object[] itsitem = new Object [10]; private int itsfront = 0; //location of front element, if any private int itsrear = -1; //location of rear element, if any public boolean isempty() { return itsrear == itsfront - 1; public Object peekfront() { if (isempty()) throw new IllegalStateException ("queue is empty"); return itsitem[itsfront]; public Object dequeue() { if (isempty()) throw new IllegalStateException ("queue is empty"); itsfront++; return itsitem[itsfront - 1]; public void enqueue (Object ob) { if (itsrear == itsitem.length - 1) adjustthearray(); itsrear++; itsitem[itsrear] = ob; private void adjustthearray() { if (itsfront > itsrear / 4) { itsrear -= itsfront; for (int k = 0; k <= itsrear; k++) itsitem[k] = itsitem[k + itsfront]; itsfront = 0; else { Object[] todiscard = itsitem; itsitem = new Object [2 * itsrear]; for (int k = 0; k <= itsrear; k++) itsitem[k] = todiscard[k]; // automatic garbage collection gets rid of todiscard The enqueue method The basic logic of the enqueue method is to increment itsrear and put the given value at that component: itsrear++; itsitem[itsrear] = ob;

14 14-14 Java Au Naturel by William C. Jones Implementing Stacks And Queues With Linked Lists We next implement a StackADT object as a linked list of Nodes. A Node object stores two pieces of information: a reference to a single piece of data of type Object and a reference to another Node object. If for instance you want to represent a sequence of three data values as a linked list of Nodes, you put the three data values in three different Node objects and have the first Node refer to the second Node, the second Node refer to the third, and the third Node not refer to any Node at all. The Node class The Node class is defined in Listing A Node object's data is referenced by itsdata and the Node that comes next after it in the linked list is referenced by itsnext. Listing 14.5 The Node class public class Node { private Object itsdata; private Node itsnext; public Node (Object data, Node next) { itsdata = data; itsnext = next; /** Return the data attribute of the Node. */ public Object getvalue() { return itsdata; /** Return the next attribute of the Node. */ public Node getnext() { return itsnext; /** Replace the data attribute of the Node. */ public void setvalue (Object data) { itsdata = data; /** Replace the next attribute of the Node. */ public void setnext (Node next) { itsnext = next;

16 14-16 Java Au Naturel by William C. Jones The peektop method is quite straightforward: First you check to make sure the stack is not empty (otherwise you throw an Exception). If the stack has at least one Node, the first Node is the top of the stack, so you simply return itstop.getvalue(). This coding is in the upper part of Listing 14.6 (see below). The pop method is the most complex of the NodeStack methods: Once you check that the stack is not empty, you discard the first Node in the linked list, since it contains the data that you are to remove. This can be done with the following statement: itstop = itstop.getnext(); That statement stores a reference to the second Node on the list in the itstop instance variable. If there was only one Node on the list in the first place, itstop.getnext() has the value null, so itstop is now null, which signals that the stack is empty. The coding for pop is in the lower part of Listing Internal invariant for NodeStacks If the abstract stack is empty, the Node value itstop is null. If the abstract stack is not empty, itstop refers to the first Node in a linked list of Nodes and itstop.getvalue() is the top element of the stack. If p is any Node in that linked list for which p.getnext() is not null, then the element p.getnext().getvalue() is the element that will be on top of the stack immediately after popping off the element p.getvalue(). The Nodes of one NodeStack are all different objects from those in any other. Listing 14.6 The NodeStack class of objects public class NodeStack implements StackADT { private Node itstop = null; public boolean isempty() { return itstop == null; public Object peektop() { if (isempty()) throw new IllegalStateException ("stack is empty"); return itstop.getvalue(); public Object pop() { if (isempty()) throw new IllegalStateException ("stack is empty"); Node todiscard = itstop; itstop = itstop.getnext(); return todiscard.getvalue(); public void push (Object ob) { itstop = new Node (ob, itstop);

7.1 Our Current Model

Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.

Chapter 3: Restricted Structures Page 1

Chapter 3: Restricted Structures Page 1 1 2 3 4 5 6 7 8 9 10 Restricted Structures Chapter 3 Overview Of Restricted Structures The two most commonly used restricted structures are Stack and Queue Both

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues 1. 2004 Goodrich, Tamassia

This lecture Abstract data types Stacks Queues ADTs, Stacks, Queues 1 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations

12 Abstract Data Types

12 Abstract Data Types 12.1 Source: 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).

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions

Module 2 Stacks and Queues: Abstract Data Types

Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Stacks (and Queues) 1 Stacks Stack: what is it? ADT Applications Implementation(s) 2 CSCU9A3 1 Stacks and ueues A stack is a very important data structure in computing science. A stack is a seuence of

STACKS,QUEUES, AND LINKED LISTS Stacks Queues Linked Lists Double-Ended Queues Case Study: A Stock Analysis Applet 1 Stacks Astack is a container of objects that are inserted and removed according to the

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Definition Course: Programming II - Abstract Data Types The ADT Queue The ADT Queue is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit addition

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Outline Computer Science 1 Stacks Mike Jacobson Department of Computer Science University of Calgary Lecture #12 1 2 Applications Array-Based Linked List-Based 4 Additional Information Mike Jacobson (University

ADTs and Modules in Java and C

CMPS 101 Algorithms and Abstract Data Types ADTs and Modules in Java and C Introduction This document introduces the concepts of Modules and ADTs, and describes how to implement them in both Java and C.

csci 210: Data Structures Stacks and Queues

csci 210: Data Structures Stacks and Queues Summary Topics stacks and queues as abstract data types implementations arrays linked lists analysis and comparison application: searching with stacks and queues

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E Chapter 5 Linked Lists Doubly Linked Lists Traversed in either direction Typical operations Initialize the list Destroy the list Determine if list empty Search list for a given

CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Queues Outline and Required Reading: Queues ( 4. except 4..4) COSC, Fall 3, Section A Instructor: N. Vlajic Queue ADT Queue linear data structure organized according to first-in/first-out (FIFO) principle!

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: 15.1-15.3. Data Structures

1.00 Lecture 35 Data Structures: Introduction Stacks, Queues Reading for next time: Big Java: 15.1-15.3 Data Structures Set of reusable classes used in algorithms, simulations, operating systems, applications

Glossary of Object Oriented Terms

Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

Common Data Structures

Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

Introduction to Stacks

Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack. What is a Stack? Stack is a data structure in which data is added

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

CHAPTER 4 ESSENTIAL DATA STRUCTURES 72 CHAPTER 4 ESSENTIAL DATA STRUCTRURES In every algorithm, there is a need to store data. Ranging from storing a single value in a single variable, to more complex

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 Lecture #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

Stacks and Queues What is a Stack? Stores a set of elements in a particular order Accessed in Last-In In-First-Out (LIFO) fashion Real life examples: Pile of books PEZ dispenser Cup trays in cafeteria

Data Structures. Topic #4

Topic #4 Today s Agenda Stack and Queue ADTs What are they Like Ordered Lists, are position oriented Use of Data Structures for Stacks and Queues arrays (statically & dynamically allocated) linear linked

Stacks & Queues. Data structures and Algorithms

Stacks & Queues Data structures and Algorithms Acknowledgement: These slides are adapted from slides provided with Data Structures and Algorithms in C++ Goodrich, Tamassia and Mount (Wiley, 2004) Outline

Data Structures Using C++ 2E. Chapter 7 Stacks

Data Structures Using C++ 2E Chapter 7 Stacks Stacks Data structure Elements added, removed from one end only Last In First Out (LIFO) FIGURE 7-1 Various examples of stacks Data Structures Using C++ 2E

4.3 Stacks and Queues. Pushdown Stacks. Data Structures and Data Types. Collections

Data Structures and Data Types 4.3 Stacks and Queues Data types Set values. Set operations on those values. Some are built in to Java: int, double, char,... Most are not: Complex, Picture, Charge, Stack,

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

COMP209 Object Oriented Programming Designing Classes 2 Mark Hall Programming by Contract (adapted from slides by Mark Utting) Preconditions Postconditions Class invariants Programming by Contract An agreement

Algorithms and Data Structures

Algorithms and Data Structures Part 2: Data Structures PD Dr. rer. nat. habil. Ralf-Peter Mundani Computation in Engineering (CiE) Summer Term 2016 Overview general linked lists stacks queues trees 2 2

Chapter 7: Queues and Deques

Chapter 7: Queues and Deques After the stack, the next simplest data abstraction is the queue. As with the stack, the queue can be visualized with many examples you are already familiar with from everyday

Stacks. The stack ADT Stack Implementation. Stack Examples. using arrays using generic linked lists using List ADT. EECS 268 Programming II 1

Stacks The stack ADT Stack Implementation using arrays using generic linked lists using List ADT Stack Examples 1 Stacks and Queues Linear data structures each item has specific first, next, and previous

10CS35: Data Structures Using C

CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

Software Engineering Techniques

Software Engineering Techniques Low level design issues for programming-in-the-large. Software Quality Design by contract Pre- and post conditions Class invariants Ten do Ten do nots Another type of summary

Announcements. FINAL EXAM Monday May 21, 1:30pm Review Session. Wednesday May 16, 7-9pm

Announcements FINAL EXAM Monday May 21, 1:30pm Review Session Wednesday May 16, 7-9pm 1 Recitation 12 Root Finding, Sorting, Stacks, Queues 2 Outline Linked Lists Sorting Queues 3 Object References Let

Algorithms and Data Structures

Basic Data Structures Page 1 BFH-TI: Softwareschule Schweiz Basic Data Structures Dr. CAS SD01 Basic Data Structures Page 2 Outline Data Structures and Abstract Data Types Linear Data Structures Implementing

Chapter 13. Pointers and Linked Lists

Chapter 13 Pointers and Linked Lists Overview 13.1 Nodes and Linked Lists 13.2 Stacks and Queues Slide 13-2 13.1 Nodes and Linked Lists Nodes and Linked Lists n A linked list is a list that can grow and

Chapter 2. Values, Variables, and Types. 2.1 Java Values in DrJava s Interaction Pane

14 Chapter 2 Values, Variables, and Types In this chapter we explore the primitive building blocks that are used to develop Java programs. We experiment with the following concepts within DrJava s interactive

CompSci-61B, Data Structures Final Exam

Your Name: CompSci-61B, Data Structures Final Exam Your 8-digit Student ID: Your CS61B Class Account Login: This is a final test for mastery of the material covered in our labs, lectures, and readings.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

DATA STRUCTURES USING C

DATA STRUCTURES USING C QUESTION BANK UNIT I 1. Define data. 2. Define Entity. 3. Define information. 4. Define Array. 5. Define data structure. 6. Give any two applications of data structures. 7. Give

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

Comp 245 Data Structures. Stacks

Comp 245 Data Structures Stacks What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO random access to other elements within the stack An

Introduction to Java A First Look

Introduction to Java A First Look Java is a second or third generation object language Integrates many of best features Smalltalk C++ Like Smalltalk Everything is an object Interpreted or just in time

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

INTERNATIONAL EDITION. Problem Solving with C++ Data Abstraction & SIXTH EDITION. Walls and Mirrors. Frank M. Carrano Timothy Henry

INTERNATIONAL EDITION Data Abstraction & Problem Solving with C++ Walls and Mirrors SIXTH EDITION Frank M. Carrano Timothy Henry Operator Meaning Associativity Usage * multiply left expr * expr / divide

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues Linda Shapiro Registration We have 180 students registered and others who want to get in. If you re thinking of dropping

Fundamentals of Java Programming

Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

UNIVERSITI MALAYSIA SARAWAK KOTA SAMARAHAN SARAWAK PSD2023 ALGORITHM & DATA STRUCTURE

STUDENT IDENTIFICATION NO UNIVERSITI MALAYSIA SARAWAK 94300 KOTA SAMARAHAN SARAWAK FAKULTI SAINS KOMPUTER & TEKNOLOGI MAKLUMAT (Faculty of Computer Science & Information Technology) Diploma in Multimedia

CS106A, Stanford Handout #38. Strings and Chars

CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes

Sequential Data Structures

Sequential Data Structures In this lecture we introduce the basic data structures for storing sequences of objects. These data structures are based on arrays and linked lists, which you met in first year

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

7-1 Java Au Naturel by William C. Jones 7-1

7-1 Java Au Naturel by William C. Jones 7-1 7 Arrays Overview In this chapter you will learn about arrays in the context of a personnel database system for a commercial company. An array lets you store

1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Fall 2007 7p-9p, Thursday, October 4 Name: NetID: Lab Section

Pseudo code Tutorial and Exercises Teacher s Version

Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy

2.6 Stacks and Queues

Stacks and Queues 2.6 Stacks and Queues Fundamental data types.! Set of operations (add, remove, test if empty) on generic data.! Intent is clear when we insert.! Which item do we remove? Stack.! Remove

(e) none of the above.

1 The default value of a static integer variable of a class in Java is, (a) 0 (b) 1 (c) Garbage value (d) Null (e) -1 2 What will be printed as the output of the following program? public class testincr

CS 2112 Spring 2014. 0 Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

CS 2112 Spring 2014 Assignment 3 Data Structures and Web Filtering Due: March 4, 2014 11:59 PM Implementing spam blacklists and web filters requires matching candidate domain names and URLs very rapidly

Linked Lists Linked Lists, Queues, and Stacks CSE 10: Introduction to C Programming Fall 200 Dynamic data structure Size is not fixed at compile time Each element of a linked list: holds a value points

Joy: Forth s Functional Cousin

Joy: Forth s Functional Cousin Manfred von Thun 9th October 2001 1 Synopsis of the language Joy The language Joy is a purely functional programming language. Whereas all other functional programming languages

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards Course Title: TeenCoder: Java Programming Course ISBN: 978 0 9887070 2 3 Course Year: 2015 Note: Citation(s) listed may represent

Stacks. Linear data structures

Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

Data Structures Using Java

Data Structures Using Java D. S. Malik P. S. Nair THOMSON COURSE TECHNOLOGY Australia Canada Mexico Singapore Spain United Kingdom United States TABLE OF Contents PREFACE XXV 1.Software Engineering Principles

D06 PROGRAMMING with JAVA

Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch20 Data Structures I PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com, for

Chapter 6: Stacks. The Stack Concept and ADT specification

Chapter 6: Stacks You are familiar with the concept of a stack from many everyday examples. For example, you have seen a stack of books on a desk, or a stack of plates in a cafeteria. The common characteristic

Stacks. Data Structures and Data Types. Collections

Data Structures and Data Types Data types Set values. Set operations on those values. Some are built in to Java: int, double, char,... Most are not: Complex, Picture, Charge, Stack, Queue, Graph,... Data

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

CS 2112 Lecture 27 Interpreters, compilers, and the Java Virtual Machine 1 May 2012 Lecturer: Andrew Myers 1 Interpreters vs. compilers There are two strategies for obtaining runnable code from a program

Programming with Data Structures

Programming with Data Structures CMPSCI 187 Spring 2016 Please find a seat Try to sit close to the center (the room will be pretty full!) Turn off or silence your mobile phone Turn off your other internet-enabled

TuringSim - An Universal Turing Machine Simulator for ios

TuringSim - An Universal Turing Machine Simulator for ios 1. Introduction Cristian Stanescu The Turing Machine is a great model for designing general purpose algorithms. Due to its simplicity and flexibility,

Chapter 7: Sequential Data Structures

Java by Definition Chapter 7: Sequential Data Structures Page 1 of 112 Chapter 7: Sequential Data Structures We have so far explored the basic features of the Java language, including an overview of objectoriented

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Nicki Dell Spring 2014

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues Nicki Dell Spring 2014 Registration We have 140 students registered and 140+ on the wait list! If you re thinking of

Checking Access to Protected Members in the Java Virtual Machine Alessandro Coglio Kestrel Institute 3260 Hillview Avenue, Palo Alto, CA 94304, USA Ph. +1-650-493-6871 Fax +1-650-424-1807 http://www.kestrel.edu/

C Compiler Targeting the Java Virtual Machine

C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One of the

Computing Concepts with Java Essentials

2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. Computing Concepts with Java Essentials 3rd Edition Cay Horstmann

Motivation. We often want to access every item in a data structure or collection in turn

Topic 13 Iterators Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over or stepping through or visiting every item in the data

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Stacks Outline The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack Stacks 2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure

AP Computer Science Java Subset

APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

Outline. 1 Denitions. 2 Principles. 4 Implementation and Evaluation. 5 Debugging. 6 References

Outline Computer Science 331 Introduction to Testing of Programs Mike Jacobson Department of Computer Science University of Calgary Lecture #3-4 1 Denitions 2 3 4 Implementation and Evaluation 5 Debugging

C++ Introduction to class and data abstraction

C++ Introduction to class and data abstraction 1 Data abstraction A data abstraction is a simplified view of an object by specifying what can be done with the object while hiding unnecessary details In

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

CHAPTER 5 The Tree Data Model There are many situations in which information has a hierarchical or nested structure like that found in family trees or organization charts. The abstraction that models hierarchical

Algorithms and Data Structures Written Exam Proposed SOLUTION

Algorithms and Data Structures Written Exam Proposed SOLUTION 2005-01-07 from 09:00 to 13:00 Allowed tools: A standard calculator. Grading criteria: You can get at most 30 points. For an E, 15 points are

Introduction to Programming System Design. CSCI 455x (4 Units)

Introduction to Programming System Design CSCI 455x (4 Units) Description This course covers programming in Java and C++. Topics include review of basic programming concepts such as control structures,

University of Twente. A simulation of the Java Virtual Machine using graph grammars

University of Twente Department of Computer Science A simulation of the Java Virtual Machine using graph grammars Master of Science thesis M. R. Arends, November 2003 A simulation of the Java Virtual Machine

Workshop on Distributed Software Management for e-science

1 Workshop on Distributed Software Management for e-science Day 2 - Software Design Lecture 4 Code Design Basics Geoff Cawood Consultant, EPCC Telephone: +44 131 650 5120 Email: geoffc@epcc.ed.ac.uk 4Low

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

Data Abstraction and Hierarchy

Data Abstraction and Hierarchy * This research was supported by the NEC Professorship of Software Science and Engineering. Barbara Liskov Affiliation: MIT Laboratory for Computer Science Cambridge, MA,

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

The Clean programming language Group 25, Jingui Li, Daren Tuzi The Clean programming language Overview The Clean programming language first appeared in 1987 and is still being further developed. It was

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

QUEUES A queue is simply a waiting line that grows by adding elements to its end and shrinks by removing elements from the. Compared to stack, it reflects the more commonly used maxim in real-world, namely,

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Quiz 4 Solutions Q1: What value does function mystery return when called with a value of 4? int mystery ( int number ) { if ( number

Answer Key. / append i at the tail of this queue and return i / public int enqueue ( int i ) ;

Answer Key 1. General Understanding (10 points) (a) What is the relationship between a method s throws clause and that checked exceptions the can be thrown during the execution of the method? (b) If a

JavaScript: Control Statements I

1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can