Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1
|
|
|
- Gertrude Walsh
- 9 years ago
- Views:
Transcription
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 and deletion of items only at one end of the sequence (the top ). The stack is a list structure, sometimes called a last-in-first-out (or LIFO) list. A stack is either empty, or it consists of a sequence of items. Access is limited to the top item on the stack at all times. push pop Item 4 Item 3 Item 2 Item 1 A stack An empty stack The ADT Stack and Recursion Slide Number 1 The term stack is intended to conjure up visions of things encountered in daily life, such as a stack of dishes in a college cafeteria or a stack of books on your desk. In common English usage, stack of and pile of are synonymous. To computer scientists, however, a stack is not just any old pile. A stack has the property that the last item placed on the stack will be the first item to be removed. This property is commonly referred to as last-in-first-out or simply LIFO. The last item placed on the stack is called the top item in the stack. Access procedures for this type of Abstract Data type can therefore only examine the top item. The LIFO property of stack seems inherently unfair. How would you like to be the first person to arrive on the stack for a movie (as opposed to a line for a movie). You would be the last person to be allowed in! Stack are not especially prevalent in everyday life. The property that we usually desire in our daily lives is first-in-first-out (or FIFO). A queue, which we will study in the next lecture, is the Abstract Data Type with the FIFO property. Most people would much prefer to wait in a movie queue (or in a line) than in a movie stack! However, while the LIFO property is not very appropriate for many day-to-day situations, it is very much needed for a large number of problems that arise in computer science. The access procedures for a stack include therefore operations such as examining whether the stack is empty (but not how many items are in the stack), inspecting the top item but not others, placing an item on top of the stack, but at no other position, and removing an item from the top of the stack, but from no other position. Stacks can therefore be seen as special lists with access procedures restricted to just the top element. 1
2 Access Procedures Constructor operations to construct a stack: i. createstack( ) // post: creates an empty Stack ii. push(newitem) // post: adds newitem at the top of the stack. Predicate operations to test Stacks i. isempty( ) // post: determines whether a stack is empty Selector operations to select items of a Stack i. top( ) // post: returns the top item of the stack. It does not change the stack. ii. pop( ) // post: changes the stack by removing the top item. The ADT Stack and Recursion Slide Number 2 This slide provides the headers of the access procedures for the ADT stack, and their respective postconditions, without the exception cases. The names push and pop given here for the operations that add and remove items to the stack are the conventional names for stack operations. So far we have only given the headers of these operations and their (partial) post-conditions. Later we will give examples of implementations. In the next slide we ll see a brief example of a program application that uses this ADT. The full post-conditions for these access procedures that include also the exception cases are given here: top( ) //post: if the stack is not empty, the item on the top is returned //and the stack is left unchanged. Throws exception if the stack is empty. pop( ) //post: if the stack is not empty, the item on the top is removed from the //stack. Throws exception if the stack is empty push(item) //Pre:item is the new item to be added //Post: If insertion is successful, item is on the top of the stack. //Throws StackException if the insertion is not successful 2
3 Using a Stack: an example A method displaystack that displays the items in a stack: The pseudocode: displaystack(astack) // post: displays the items in the stack astack; while (!astack.isempty( ) ) { newchar = astack.top( )); astack.pop( ); Write newchar //end while The ADT Stack and Recursion Slide Number 3 As it is the case for an ADT list, also for stacks once the operations of the ADT stack have been satisfactorily specified, applications can be designed that access and manipulate the ADT s data, by using only the access procedures without regard for the implementation. So far, in fact, we haven t seen or used any particular implementation of stacks. A little example is considered here. Suppose that we want to display the items in a stack. The wall between the implementation of the ADT and the rest of the program prevents the program from knowing how the stack is being stored, i.e. which data structure has been used to implement the stack. The program can, however, still access the items of a stack by means of the access procedures. In this case the method displaystack, can use the operation astack.top( ) to access the top item of a stack, and the operation astack.pop() to change the stack by removing the item on the top. 3
4 Axioms for ADT Stacks The access procedures must satisfy the following axioms, where Item is an item and astack is a given stack: 1. (astack.createstack( ) ).isempty = true 2. (astack.push(item)).isempty() = false 3. (astack.createstack( )).top( ) = error 4. (astack.push(item )).top( ) = Item 5. (astack.createstack( )).pop( ) = error 6. (astack.push(item)).pop( ) = astack A stack is like a list with top( ), pop( ) and push(item) equivalent to get 1 st item, remove 1 st item and add item at the beginning of a list. The ADT Stack and Recursion Slide Number 4 In this slide I have listed the main axioms that the access procedures for an ADT stack have to satisfy. In this case, we have two axioms for each operation. Note that the access procedures for a stack are somewhat equivalent to the access procedures for a list described in the previous lecture. In particular, the top( ) procedure for a stack can be seen as equivalent to the get(1) procedure for a list, which takes the first element of a given list. In the same way, the procedure pop( ) for a stack is equivalent to the procedure remove(1), which removes the first element in a list, whereas the procedure push(item) is equivalent to the procedure add(1,item), which add the given new item to the first position in a list. In the next slides we ll look at the two different types of implementations of a stack, one based on array and the other based on linked lists. The definition of the data structure for a stack in the case of a dynamic implementation, will further illustrate the fact that stacks are essentially lists with specific use of their access procedures. 4
5 Interface StackInterface for the ADT Stack public interface StackInterface{ public boolean isempty(); //Pre: none //Post: Returns true if the stack is empty, otherwise returns false. public void push(object item) throws StackException; //Pre:item is the new item to be added //Post: If insertion is successful, item is on the top of the stack. //Post:Throw StackException if the insertion is not successful public Object top( ) throws StackException; //Pre: none //Post: If stack is not empty, the item on the top is returned. The stack is left unchanged //Post: Throws StackException if the stack is empty. public void pop( ) throws StackException; //Pre: none //Post: If stack is not empty, the item on the top is removed from the stack. //Post: Throws StackException if the stack is empty. The ADT Stack and Recursion Slide Number 5 The interface StackInterface given in this slide provides the main definition of each access procedure for the ADT stack. As in the case of the ADT list, the constructor createstack( ) is not included here as it is normally given as constructor of the particular Java class that implements the Stack. The two main types of implementation (array-based, reference-based) for a stack are classes that implement this interface. This interface provides, therefore, a common specification for the two implementations that we are going to illustrate in the next few slides. An example of the StackException for a stack can be the following: public class StackException extends java.lang.runtimeexception { public StackException(String s){ super(s); // end constructor // end StackException Note that this exception can be avoided by including in the implementation of the access procedure a check to see whether the stack is empty before calling the procedures. In the case of push(item), if the implementation is a static implementation it is also important to consider exceptions caused by the underlying array data structure being full. A private method, called isfull, can be defined for the static implementation of a stack, to check whether the underlying array is full before calling the procedure push(item). In a reference-based implementation, such exception is not necessary since the memory is dynamically allocated and not fixed. 5
6 Data structure class StackArrayBased{ final int MAX_STACK = 50; private Object items[ ]; private int top; ; Course: Programming II - Abstract Data Types Array-based Implementation of a Stack top k k MAX_STACK-1 public class StackArrayBased implements StackInterface{ final int MAX_STACK = 50; private Object items[ ]; private int top; public StackArrayBased( ){ items = new Object[MAX_STACK]; top = 1; // end default constructor; public boolean isempty( ){ return top < 0; // end isempty The ADT Stack and Recursion Slide Number 6 The data structure for a static implementation of a stack uses an array of Objects called items, to represent the items in a stack, and an index value top such that items[top] is the stack s top. When a stack is created it does not include any item at all. In this case the value of the index top is set to 1. This allows us to test in general when a stack has become empty by just checking whether the value of top is a negative integer. The partial implementation of StackArrayBased given in this slide gives the definition of the default constructor and the implementation of the method isempty. In the same way it would be possible to check whether a stack is full by testing whether the value of top has become equal to MAX_STACK-1. The addition of items in the stack, starts from position 0 in the array. Each time a push procedure is called, the value of top is incremented by 1 to point to the next top free cell in the array, and the new item is assigned to this position. Similarl;y, each time a pop( ) procedure is called, the item at the top of the stack should be removed. In this static implementation, this is simply given by decrementing the value of top by 1. The array will still include the value but no longer point to it. An example implementation for the procedure pop( ) is given here: Public void pop( ) throws StackException{ if (!isempty( ) ) { top = top 1; else { throw new StackException( Exception on pop: stack empty ); 6
7 Dynamic Implementation of a Stack 5 13 top class StackReferenceBased{ private Node top; Data structure class Node{ Object item; Node next;. 10 public class StackReferenceBased implements StackInterface{ private Node top; public StackReferenceBased( ){ top = null; // end default constructor; public boolean isempty( ){ return top == null; // end isempty The ADT Stack and Recursion Slide Number 7 Many applications require a reference-based (or dynamic) implementation of a stack so that the stack can grow and shrink dynamically. A diagrammatical representation of a dynamic implementation of a stack is given in the left-hand side of this slide. In this picture, top is a reference to the head of a linked list of items. The implementation uses the same node class used for the linked list in the previous lecture. We give here the implementation of the other access procedures: public void push(object newitem){ top = new Node(newitem, top); // end push public Object top( ) throws Stack Exception { if (! isempty) { return top.getitem( ); else throw new StackException( Stack is empty ); public void pop( ) throws StackException { if (!isempty) { top = top.getnext; 7
8 Recursion Java uses stacks to implement method activations and recursion. General criteria: A representation of each variable declared within a method is created on entry to (or activation of) that method, and destroyed on exit from it. A distinct representation of each variable is created on each re-entry to (or re-activation of) a method. In particular, these criteria enable Java to implement recursive methods, by having as many instances of the declared variables in existence as activations have been made of the method. But only the most recent are accessible to the program. The ADT Stack and Recursion Slide Number 8 In the remainder of this lecture we will have a closer look at how methods are executed in Java and in particular how recursion is handled in Java. The reason why this is given together with the introduction to the ADT Stack, is because the underlying data structure used by Java for handling both method activations and recursive calls of a method is in fact a stack. 8
9 Activation records and execution stack An activation record is a memory block created at each method activation, which includes: top Method s local variables Method s parameters Return address The return address is information about the correct location to return to after the method has been executed. An execution stack stores the collection of activation records: each activation of a method pushes the next activation record on top of the execution stack. The ADT Stack and Recursion Slide Number 9 Java keeps track of the activation of a method (say) A, in the following way. When a method A is activated (whether recursive or not) the computer temporarily stops the execution of the current method (this could well be a main program). Before actually executing the method A, some information is saved that will allow the computer to return to the correct location after the method A is completed. The computer also provides memory for the parameters and local variables that the method A uses. This memory block is called activation record and essentially provides all the important information that the method A needs to work. It also provides information as to where the method should return when it is done with its computation. Once this block is created, the method A is then executed. If the execution of method A should encounter an activation of another method, recursive or otherwise, then the first method s computation is temporarily stopped. This is because the second method must be executed first before the first method can continue. Information is saved that indicates precisely where the first method should resume when the second method is completed. An activation record for the second method is then created and placed on top pf the other existing activation records. The execution then proceeds to the second method.. When this second method is completed, its activation record provides the information as to where the computation should continue. The execution record of this second method is then removed from the top of the collection of existing activation records. All the activation records so created are stored by the program in a stack data structure called execution stack. Each newly created activation record is pushed on top of the execution stack and at the end of execution of a method, its activation record is popped off the execution stack. This mechanism is used for both recursive and non-recursive methods. We will now see, in particular, examples of recursive methods. 9
10 Iteration and Recursion Course: Programming II - Abstract Data Types Many algorithms have alternative iterative and recursive forms: E.g.: The Factorial function: int Factorial(int n){ //pre: n 0. It evaluates n! iteratively int temp=1; if (n = = 0) then return 1 else { for (int i=1; i n; i++) temp = temp*i; return temp; Iterative algorithm int Factorial(int n){ //pre: n 1. It evaluates n! recursively if (n = = 0) then return 1 else return n*factorial(n-1); Recursive algorithm The ADT Stack and Recursion Slide Number 10 Many algorithms can have either an iterative or recursive form. In this slide I have given the example of the algorithm that calculates the factorial of a natural number in both its two forms. Let s see what happens when we run for instance the recursive algorithm for the case of Factorial (3). 10
11 Executing the recursive method Factorial(3) n=3 n=2 A: factorial(2) push A: factorial(1) return =? n=1 return =? A: factorial(0) return address (A) return address return (A) =? n=0 return = 1 return address (A) return address (A) n=1 n=2 A: factorial(0)=1 n=3 A: factorial(1)=1 return =? 1 A: factorial(2)=2 return =? 2 return =? 6 return address (A) (A) return address (A) return address (A) The ADT Stack and Recursion Slide Number 11 pop This is an example run of recursive call. Note this slide is animated. At each creation of a new activation record that is pushed in the execution stack, the current activation record becomes grey, as it is temporarily stopped. At the end, on the last recursive call, the operation is a simple return instruction. The last activation record is then destroyed or popped off the stuck. And the previous activation record becomes activated (in the activation it becomes white again)... until we reach the activation record at the bottom of the stuck and the program is then completed. 11
12 Example2: The Fibonacci function int Fib(int n){ //pre: n>0. It evaluates Fib(n) recursively //post: returns the nth Fibonacci number // of order 2 if (n 2) then return 1; else return (Fib(n-1)+Fib(n-2)); // end Fib int Fib(int n){ //pre: n>0. It evaluates Fib(n) iteratively //post: returns the nth Fibonacci number // of order 2 int i, this, previous, temp; if (n 2) then return 1 else { this = 1; previous = 1; i = n; do { // end Fib while (i > 2); return this; temp = previous+this; previous = this; this=temp; i--; The ADT Stack and Recursion Slide Number 12 This is another example of an algorithm that can be executed either recursively or iteratively. The algorithm is the function that calculates the nth Fibonacci number of order 2. You should already know what the Fibonacci numbers are. These are number that form a special sequence defined as follow: Fib(1) = 1; Fib(2) = 1; Fib(n) = Fib(n-2) + Fib(n-1), for any n>2 The recursive algorithm used here is called binary recursive, because it makes two recursive calls on smaller problems (i.e. smaller numbers). There are other types of recursive algorithms, but we are not going to go into more detail in this part of the course.. If you are interested you can look at the text book on data structures for more information about recursive algorithms. 12
13 Recursion vs Iteration Recursion provides us with the simplest and most natural solution to a problem. But it can be costly. Tail recursion is a particular pattern of recursion that can be easily transformed into iteration: Definition: A method is tail recursive if there is no code to be executed after the recursive call. public static int listlength(node head) { if (head = = null) return 0; else return 1+ listlength(head.next) //end recursive form public static int listlength(node head) { Node cursor; int answer = 0; for (cursor = head; cursor!=null; cursor= cursor.next) { answer++; return answer; //end iterative form The ADT Stack and Recursion Slide Number 13 Recursion can sometime be costly, even though it might seem to be the most natural solution to a problem. Since each recursive call creates an activation record in the execution stack, if the sequence of recursive calls continues for a long time before the stopping case occurs, then we ll end up with a huge execution stack of activation records. In this case we say that the recursive algorithm is costly in space. It is possible that the size of the execution stack becomes too large for the system resources. In this case Java would issue a StackOverflowError. Because of this possibility, it is always important to have some idea of the maximum number of recursive calls needed before reaching a stopping case. This number is called depth of recursion. When the depth is likely to be too big and cause an overflow, the iterative form of the same algorithm should be used instead. One type of recursion that is easy to eliminate and transform into an iterative form, is tail recursion. This is when there is no code to be executed after the recursive call. An example of tail recursion is given in this slide together with its corresponding iterative algorithm. In general, a tail recursion has an if statement which checks for the final directly solvable case, followed by a recursive call. To transform this algorithm into its iterative form, we need just to replace the recursive calls with a loop statement and evaluation and assignment of the parameters used in the recursive call. Another typical example application of recursion is the Tower of Hanoi. It s fun. So, if you have some spare time I invite you to look at it in your text book. 13
14 An ADT Stack is: Course: Programming II - Abstract Data Types Summary A linear sequence of arbitrary number of items, whose access procedures have a last-in, first-out (LIFO) behaviour. A strong relationship between recursion and stacks exists. Most implementations of recursion maintain an execution stack of activation records. Recursion: Is a technique that solves a problem by solving a smaller problem of the same type. Some recursive solutions are much less efficient than a corresponding iterative solution, due to the overhead of method calls. Iterative solutions can be derived from recursive solutions. The ADT Stack and Recursion Slide Number 14 14
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
What Is Recursion? Recursion. Binary search example postponed to end of lecture
Recursion Binary search example postponed to end of lecture What Is Recursion? Recursive call A method call in which the method being called is the same as the one making the call Direct recursion Recursion
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
The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!
The Tower of Hanoi Recursion Solution recursion recursion recursion Recursive Thinking: ignore everything but the bottom disk. 1 2 Recursive Function Time Complexity Hanoi (n, src, dest, temp): If (n >
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!
STACKS,QUEUES, AND LINKED LISTS
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
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
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
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
St S a t ck a ck nd Qu Q eue 1
Stack and Queue 1 Stack Data structure with Last-In First-Out (LIFO) behavior In Out C B A B C 2 Typical Operations Pop on Stack Push isempty: determines if the stack has no elements isfull: determines
DATA STRUCTURE - STACK
DATA STRUCTURE - STACK http://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm Copyright tutorialspoint.com A stack is an abstract data type ADT, commonly used in most programming
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
Analysis of a Search Algorithm
CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,
MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push) -----------------------------------------
=============================================================================================================================== DATA STRUCTURE PSEUDO-CODE EXAMPLES (c) Mubashir N. Mir - www.mubashirnabi.com
The ADT Binary Search Tree
The ADT Binary Search Tree The Binary Search Tree is a particular type of binary tree that enables easy searching for specific items. Definition The ADT Binary Search Tree is a binary tree which has an
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
Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.
Recursion Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive. Why recursion? o For many problems, the recursion solution is more natural than the alternative
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
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
A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:
Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)
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
16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution
16. Recursion COMP 110 Prasun Dewan 1 Loops are one mechanism for making a program execute a statement a variable number of times. Recursion offers an alternative mechanism, considered by many to be more
1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.
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
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,
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
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
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
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
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
Linked Lists Linked Lists, Queues, and Stacks
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
Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
CS 2412 Data Structures. Chapter 2 Stacks and recursion
CS 2412 Data Structures Chapter 2 Stacks and recursion 1 2.1 Stacks A stack is a data structure in which all insertions and deletions of entries are made at one end, called top of the stack. Examples:
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.
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
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
Introduction to Data Structures
Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate
Linked Lists, Stacks, Queues, Deques. It s time for a chainge!
Linked Lists, Stacks, Queues, Deques It s time for a chainge! Learning Goals After this unit, you should be able to... Differentiate an abstraction from an implementation. Define and give examples of problems
Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16
Queues and Stacks Atul Prakash Downey: Chapter 15 and 16 Queues Queues occur in real life a lot. Queues at checkout Queues in banks In software systems: Queue of requests at a web servers Properties of
Data Structures and Algorithms Stacks and Queues
Data Structures and Algorithms Stacks and Queues Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/23 6-0: Stacks and
Universidad Carlos III de Madrid
Universidad Carlos III de Madrid Algorithms and Data Structures (ADS) Bachelor in Informatics Engineering Computer Science Department Lists, Stacks and Queues. Authors: Isabel Segura Bedmar April 2011
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
Chapter 8: Bags and Sets
Chapter 8: Bags and Sets In the stack and the queue abstractions, the order that elements are placed into the container is important, because the order elements are removed is related to the order in which
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
COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012
Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about
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
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
PES Institute of Technology-BSC QUESTION BANK
PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions
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
Ordered Lists and Binary Trees
Data Structures and Algorithms Ordered Lists and Binary Trees Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/62 6-0:
DATA STRUCTURE - QUEUE
DATA STRUCTURE - QUEUE http://www.tutorialspoint.com/data_structures_algorithms/dsa_queue.htm Copyright tutorialspoint.com Queue is an abstract data structure, somewhat similar to stack. In contrast to
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.
CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++
Brad Rippe CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++ Recursion Recursion CHAPTER 14 Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively
Binary Heap Algorithms
CS Data Structures and Algorithms Lecture Slides Wednesday, April 5, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks [email protected] 2005 2009 Glenn G. Chappell
Data Structures and Data Manipulation
Data Structures and Data Manipulation What the Specification Says: Explain how static data structures may be used to implement dynamic data structures; Describe algorithms for the insertion, retrieval
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
Recursion vs. Iteration Eliminating Recursion
Recursion vs. Iteration Eliminating Recursion continued CS 311 Data Structures and Algorithms Lecture Slides Monday, February 16, 2009 Glenn G. Chappell Department of Computer Science University of Alaska
Lecture Notes on Linear Search
Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 29, 2013 1 Introduction One of the fundamental and recurring problems in computer science is
LINKED DATA STRUCTURES
LINKED DATA STRUCTURES 1 Linked Lists A linked list is a structure in which objects refer to the same kind of object, and where: the objects, called nodes, are linked in a linear sequence. we keep a reference
Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!
ECE 551 C++ Programming, Data structures, and Algorithms Abstract Data Type: Stack Last In First Out (LIFO) 1 2 2 1 4 3 1 3 4 Stacks in Programming Worst line ever! 5 3 1 5 Stacks are not useful for waiting
Lecture 12 Doubly Linked Lists (with Recursion)
Lecture 12 Doubly Linked Lists (with Recursion) In this lecture Introduction to Doubly linked lists What is recursion? Designing a node of a DLL Recursion and Linked Lists o Finding a node in a LL (recursively)
Data Structures and Algorithms C++ Implementation
BK TP.HCM Ho Chi Minh City University of Technology Faculty of Computer Science and Engineering BK TP.HCM Data Structures and Algorithms C++ Implementation Huỳnh Tấn Đạt Email: [email protected] Home
Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go
Debugging ESE112 Java Programming: API, Psuedo-Code, Scope It is highly unlikely that you will write code that will work on the first go Bugs or errors Syntax Fixable if you learn to read compiler error
Data Structure with C
Subject: Data Structure with C Topic : Tree Tree A tree is a set of nodes that either:is empty or has a designated node, called the root, from which hierarchically descend zero or more subtrees, which
Data Structures and Algorithms
Data Structures and Algorithms CS245-2016S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list
Converting a Number from Decimal to Binary
Converting a Number from Decimal to Binary Convert nonnegative integer in decimal format (base 10) into equivalent binary number (base 2) Rightmost bit of x Remainder of x after division by two Recursive
Basic Data Structures and Algorithms
Tutorial 3 Basic Data Structures and Algorithms THINGS TO LOOK FOR 3.0 INTRODUCTION 3.1 Array Based Containers Definition and uses of containers. Array and list based containers. Designing and building
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
TREE BASIC TERMINOLOGIES
TREE Trees are very flexible, versatile and powerful non-liner data structure that can be used to represent data items possessing hierarchical relationship between the grand father and his children and
Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser
Algorithms and Data Structures Stack, Queues, and Applications Ulf Leser Content of this Lecture Stacks and Queues Tree Traversal Towers of Hanoi Ulf Leser: Alg&DS, Summer semester 2011 2 Stacks and Queues
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
Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }
Functions Recursion C++ functions Declare/prototype int myfunction (int ); Define int myfunction (int x){ int y = x*x; return y; Call int a; a = myfunction (7); function call flow types type of function
Lecture Notes on Binary Search Trees
Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 March 17, 2010 1 Introduction In the previous two lectures we have seen how to exploit the structure
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
Unordered Linked Lists
Unordered Linked Lists Derive class unorderedlinkedlist from the abstract class linkedlisttype Implement the operations search, insertfirst, insertlast, deletenode See code on page 292 Defines an unordered
Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types
EECS 281: Data Structures and Algorithms The Foundation: Data Structures and Abstract Data Types Computer science is the science of abstraction. Abstract Data Type Abstraction of a data structure on that
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
Thread Synchronization and the Java Monitor
Articles News Weblogs Buzz Chapters Forums Table of Contents Order the Book Print Email Screen Friendly Version Previous Next Chapter 20 of Inside the Java Virtual Machine Thread Synchronization by Bill
Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction
bstract ata Types Previous lectures: algorithms and their efficiency analysis. oming lectures: data structures In this lecture: bstract data types Ts as a design tool Examples: integer T, List T ata Types
Solving Problems Recursively
Solving Problems Recursively Recursion is an indispensable tool in a programmer s toolkit Allows many complex problems to be solved simply Elegance and understanding in code often leads to better programs:
Data Structure [Question Bank]
Unit I (Analysis of Algorithms) 1. What are algorithms and how they are useful? 2. Describe the factor on best algorithms depends on? 3. Differentiate: Correct & Incorrect Algorithms? 4. Write short note:
Data Structures Using C++
Data Structures Using C++ 1.1 Introduction Data structure is an implementation of an abstract data type having its own set of data elements along with functions to perform operations on that data. Arrays
Abstract Data Types. Chapter 2
Chapter 2 Abstract Data Types The second idea at the core of computer science, along with algorithms, is data. In a modern computer, data consists fundamentally of binary bits, but meaningful data is organized
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
Data Structures and Algorithms Written Examination
Data Structures and Algorithms Written Examination 22 February 2013 FIRST NAME STUDENT NUMBER LAST NAME SIGNATURE Instructions for students: Write First Name, Last Name, Student Number and Signature where
Lecture Notes on Stacks & Queues
Lecture Notes on Stacks & Queues 15-122: Principles of Imperative Computation Frank Pfenning, André Platzer, Rob Simmons Lecture 9 February 12, 2013 1 Introduction In this lecture we introduce queues and
Data Structures and Algorithms Lists
Data Structures and Algorithms Lists Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science University of San Francisco p.1/19 5-0: Abstract Data Types An
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
1 Description of The Simpletron
Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies
What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara
CMPSC 24: Lecture 13 Recursion Divyakant Agrawal Department of Computer Science UC Santa Barbara 5/12/10 1 Lecture Plan Recursion General structure of recursive soluions Why do recursive soluions terminate?
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
COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.
COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms 1 Activation Records activation declaration location Recall that an activation
22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department http://www.cs.uiowa.edu/~hzhang/c31/
22c:31 Algorithms Ch3: Data Structures Hantao Zhang Computer Science Department http://www.cs.uiowa.edu/~hzhang/c31/ Linear Data Structures Now we can now explore some convenient techniques for organizing
COMPUTER SCIENCE. Paper 1 (THEORY)
COMPUTER SCIENCE Paper 1 (THEORY) (Three hours) Maximum Marks: 70 (Candidates are allowed additional 15 minutes for only reading the paper. They must NOT start writing during this time) -----------------------------------------------------------------------------------------------------------------------
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
Application of Stacks: Postfix Expressions Calculator (cont d.)
Application of Stacks: Postfix Expressions Calculator (cont d.) Postfix expression: 6 3 + 2 * = FIGURE 7-15 Evaluating the postfix expression: 6 3 + 2 * = Data Structures Using C++ 2E 1 Application of
15-150 Lecture 11: Tail Recursion; Continuations
15-150 Lecture 11: Tail Recursion; Continuations Lecture by Dan Licata February 21, 2011 In this lecture we will discuss space usage: analyzing the memory it takes your program to run tail calls and tail
Sources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
Section IV.1: Recursive Algorithms and Recursion Trees
Section IV.1: Recursive Algorithms and Recursion Trees Definition IV.1.1: A recursive algorithm is an algorithm that solves a problem by (1) reducing it to an instance of the same problem with smaller
recursion, O(n), linked lists 6/14
recursion, O(n), linked lists 6/14 recursion reducing the amount of data to process and processing a smaller amount of data example: process one item in a list, recursively process the rest of the list
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,
