Sets and Sequences vs. Linked Lists

Size: px
Start display at page:

Download "Sets and Sequences vs. Linked Lists"

Transcription

1 Sets and Sequences vs. Linked Lists Florent Bouchez Tichadou September 24, 2018 We have seen previously that it is possible to use arrays (low-level structure) to hold sets or sequences (high-level structures). Arrays have nice properties such as a compact storage in memory, and constanttime memory access of elements given an index. However, they also have limitations, for instance the size is fixed, and inserting new elements take time when the ordering is important (e.g., in a sequence): a lot of elements must be shifted to make room for the new one. In this document, we will discover another low-level data structure that does not have these limitations (but also has limitations of its own): the linked lists. 1 Memory model Before introducing linked lists, we need to make sure we understand how computers memories work: the memory is like a giant array, where we can store values. The indices are called memory addresses, and the content is a value usually stored using 32 or 64 bits. From the memory point of view, the content has not type. This is the role of the program to know the type of what is stored, and interpret correctly the contents. For instance, the binary value can be interpreted either as the integer value, the True boolean value, the character string "Algo", or... the memory address 0x416c676f (hexadecimal representation). It is then possible to store memory addresses in memory. This is for instance the case for an array of character strings: the array does not actually contain the characters, but instead addresses of the starts of character strings (see Figure 1a). When we want to access a string, given its index in the array, the program only has to follow the link stored in the array, i.e., go to the address. We will use this technique to build a linked list, i.e., an object containing multiple elements called cells so that each cell contains two fields: one to store the element and the other to store the address of the next cell (see Figure 1b). Given the address of the first cell (usually called the head ), it is then possible to access all the cells one after the other by following the links until the end of the list (called the tail, and pointing to the Nil (or Null) address). 2 Linked lists Contrary to arrays, elements of a linked list are not stored contiguously in memory. It is then very easy to add a new element to a linked list: we need to reserve some space in memory for a new cell and modify the links (memory addresses) so that the list now goes through the new cell. Algorithmically, we need a mechanism to go from one cell to the next one. We prefer not to stick on an implementation based on memory addresses ( pointers ), which is dependent of a programming language. We will use the general mechanism of references to define our cells. Type and variable declaration. Creating a list with one element. type Cell: { val: element, next: reference on Cell} type Linked list: { head: reference on Cell} cel: Cell list: Linked list cel Ð new Cell cel.value Ð 42 cel.next Ð Nil list.headð cel INF301 1

2 Memory tab Memory head "Hello" "vraiment" "super" "sympa!" "World!" "L algorithmique" "c est" (a) Array of strings (b) Linked list of integers Figure 1: Memory representation of an array of addresses and a linked list. 3 Sequences and linked lists A linked list can hold an arbitrarily big number of elements (the limit being the machine s memory). Its length (number of elements) is dynamic and it is easy to add a new element while keeping the existing order. This low-level data structure is a very good candidate for storing high-level sequences! It is also a good choice for a set if we already know that the length will vary a lot. At low-level, a sequence can be directly represented using a linked list, i.e., a reference on a cell: the head of the list. Sometimes, its is also valuable to keep other references, such as one for the tail of the list (the last cell), or a reference on the previous cell (doubly linked list, see exercises at the end of the document). Declaring a sequence type Sequence: Linked list S: Sequence cel: Cell Printing a sequence print (cel.value) The next sections give low-level implementations of the usual operations on sequences. 3.1 Sequence creation, access to elements and successors To create an empty sequence, we need a reference on... nothing! Indeed, an empty sequence does not contain any cell. To access en element, given a reference on its cell, we use its value field. To access the successor of an element, we use the next field of its cell. S: Sequence Ð Nil /* Empty sequence */ print ("The cell contains: ", cel.value) cel.val Ð cel.val`12 /* modification */ /* on to the next one */ Representations in memory of an empty sequence and a cell containing 12. INF301 2

3 cel... Note: in a linked list, it is not possible to directly access the i th element as we would normally do in an array: we need to start from the head and follow the next links as many times as required (cf. next section). 3.2 Iterating on all element and computing the length In order to traverse a linked list, we first access the head of the list, then to successive elements one after the other by using the links. To compute the length, we use the same scheme while incrementing a counter. 1 Traversal and printing Computing the length Accessing the i th element print (cel.value) ; lengthð 0 length Ð length`1 do i times Drawing of the following invariant when computing the length: length contains the number of cells before the one referenced by cel in the sequence. cel length 0 length 4 cel length 8 cel Simple Search of an element Searching for an element, or testing whether an element belongs to a sequence or not, is a direct application of the iteration schemes on linked lists. We propose here three versions that return True if the value belongs to the sequence, and False otherwise. The first one uses a boolean that remembers whether the element was seen in the sequence or not, while the second and third ones stop as soon as the element is found. The third algorithm is the most elegant one, but only works in a function, since the return allows us to break out of the loop. The second algorithm shows a classical scheme where the loop exit depends on two conditions: we could either be at the end of the sequence, or on the found element. We then have to test again one of the conditions to know the exit status. 1 If this operation is used a lot, it is also possible to store a length field in the list data structure alongside the head field. INF301 3

4 Simple search Double condition loop Loop exit using return search (S, v) found Ð False if cel.value = v then found Ð True return found search (S, v) while cel Nil and cel.value v do return cel Nil search (S, v) if cel.value = v then return True return False Important For the second search algorithm, the order of the conditions in the while loop is very important: it is of utmost importance to verify first that cel is not Nil before testing cel.value. Otherwise, we would ask for the field of a potentially non-existing object, which is an algorithmic mistake, and in the case of a real program, source of nasty bugs. For the same reason, after exiting the loop, we can only test if cel is Nil and not the other condition. 3.3 Inserting an element Order is import in sequences. We distinguish three cases: 1. inserting at the beginning of a sequence, i.e., at the head; 2. inserting after an element, i.e., after a given cell; 3. inserting at the end of a sequence, i.e., at the tail. To insert at the head, we create a new cell whose successor in the current head, then the head becomes that cell. Inserting after a particular element is easy when we have a reference on the cell c of that element: similarly to the insertion at the head, we create a new cell whose successor is c.next, then we update c.next so that it points to this new cell. Finally, inserting at the tail requires to first find the tail; then inserting is done as after it (and in that case c.next is Nil), unless the list is empty (there is no tail), in which case we simply create a new cell which becomes the head (and the tail). Warning: in all cases, the order in which modifications are performed is important! Suppose we start by modifying so that it refers to the new cell, then we have lost the initial head (and the full list with it!). insert_first (S,x) cel Ð new Cell cel.value Ð x cel.next Ð Ð cel insert_after (S,x,pred) cel Ð new Cell cel.value Ð x cel.next Ð pred.next pred.nextð cel INF301 4

5 insert_last (S,x) if Nil then insert_first (S,x) else tail Ð while tail.next Nil do tail Ð tail.next insert_after (S,x,tail) Inserting 12, 18 and 42 respectively at the beginning, after 3, and at the end of a sequence. Numbers on new links show the order of modification. Crossed-out links show connections that are lost due to modifications numbered Searching and deleting an element To delete an element, we need to make the predecessor cell point to the successor, then free the element s cell (so that the memory does not get saturated eventually). The main problem here is that it is easy to access the successor (by following the next link), however it is not directly possible to get the predecessor: we must start again from the head and traverse the list! It is highly recommended, if we know that we might delete an element, to keep a reference also on the predecessor to avoid a new traversal. We present here an improved search function that returns both a reference on the cell of the element we are looking for (or Nil if not found), and a reference on the cell of the predecessor (or Nil if at the head of the list). Note: again, the order of comparisons in the while loop is very important: we must first verify that cel is not Nil before testing cel.value. Likewise, when deleting, we only free the cell when we have finished accessing its fields. search (S, x) pred Ð Nil while cel Nil et cel.value x do pred Ð cel return (cel, pred) delete (S, x) (cel, pred) Ð search (S, x) if cel Nil then Error ("Element not found!) if pred Nil then Ð cel.next else pred.next Ð cel.next free (cel) Deleting the head, an element in the middle, and the tail of a linked list. INF301 5

6 3.5 Swap of two elements In order to swap two elements, we must modify all links between the predecessors and the successors of the cells of these elements. Again, if we know we will perform a swap, it is important to keep a reference on the predecessors so we don t have do traverse the list again. We have here a corner case we need to handle: if one of the elements is the head of the list. Since we don t want to write three times the same error-prone code, we start by creating a fictional cell that becomes the head. Now we know the predecessors will never be Nil (we must give the fictional cell a value that will never be searched, or modify the search function so that it ignores this cell). Note: another corner case: when the two elements are consecutive. The proposed algorithm handles this case. Verification that it behaves as expected is left as an exercise to the reader (trace the algorithm s execution). swap (S, x, y) fictional Ð new Cell fictional.next Ð Ð fictional (cel x, pred x ) Ð search (S, x) (cel y, pred y ) Ð search (S, y) pred x.next Ð cel y pred y.next Ð cel x tmp Ð cel x.next cel x.next Ð cel y.next if cel x pred y then cel y.next Ð cel x ; else cel y.next Ð tmp; Ð fictional.next free (fictional) Swapping elements 4 and 13. fictional tmp pred x cel x pred y cel y 2 1 INF301 6

7 4 Exercises 4.1 Revisiting previous exercises Linked lists are a low-level possibility to implement the set and sequence data structures. It is then possible to re-use the exercises from the Set and Sequences vs. Arrays document and change all the low-level algorithms (using arrays) to algorithms using linked lists. Doing so will also be very helpful to make sure you understand the difference between high-level and lowlevel: if your high-level algorithm cannot be implemented in low-level using a linked list, it means you are implicitly supposing your set or sequence is stored in a array Special linked-list exercises The following exercises could of course also use arrays but linked-lists here are either well adapted or introduce interesting notions. Exercise 1 (Insert before) We have seen previously how to insert a new cell after a given cell. Give the algorithm to insert before a given cell. Exercise 2 (Separating in two) Given a sequence S using a linked list. We want to separate the sequence into S and S2 so that every other element from the initial sequence stays in S while all others go into S2. We want to keep the original ordering and use only modifications of links (no creation or removal of cells). 1. Draw on an example the initial state of the sequence as well as the final state (draw links with a different color). 2. Re-draw the example but in an intermediate state (during execution of the separation): some part of the sequence is already separated while the rest awaits processing. This drawing is your loop invariant. 3. Identify on your previous drawing the modification(s) you need to perform that one more cell is processed. This represent the body of your loop and must satisfy the invariant (keep the same state at the end of the iteration to prepare for the next one). 4. Deduce the body of your loop. Now you only need to write the initialisation part (get to the initial state before the loop) and the stop condition (loop test). Start the exercise again but separating the sequence based on the elements (integers): all the elements ě 0 stay in S while the others go in S2. Exercise 3 (Waiting queue) We wand to model a waiting queue of customers at the post office. We use a sequence represented as a linked list of the FIFO type (First In First Out): the first to enter in the first to get out. When a new customer comes, he/she must be inserted at the end of the sequence by calling a function wait. When a counter is available, the customer at the beginning of the sequence is being attended to using the function attend. 1. Give an implementation of functions wait (name: string) and attend (): string. 2. To insert at the end, we first need to find the tail of a linked list which is costly. We would like to keep a reference on the tail, i.e., the last cell of the list. Modify the data structure as well as the function wait so that the cost of inserting is now independent of the size of the waiting queue. INF301 7

8 Exercise 4 (Both ways) Let us consider a playing card game with two people. This game starts with a row of five cards randomly picked up and placed face up. At its turn, each player can either take the first or last card of the row, or add a new card (randomly picked from the deck) at the beginning or the end of the row. We want to propose a simulator of the game. We choose to implement the row of cards as a sequence using linked lists. A linked list would be efficient for one of the extremity, but slow for the other extremity. 1. Propose an extension to the data structure so the lists are now doubly linked: each cell has a reference to the next one, but also to the previous one. 2. Give the algorithms for inserting and deleting at the beginning or the end of a sequence for your doubly linked list. 3. Suppose we also want to insert and delete at any position in the sequence. Give the necessary algorithms. Exercise 5 (The pancakes maker) The local pancake shop employs a very good chef, but she has a bit of an OCD with those. She puts then in a big stack, but the stack has to be perfectly ordered: from the largest pancake at the bottom to the smallest one at the top. To modify the stack, the chef only has her spatula: she can insert it between any two pancakes, and flip over in one move all the pancake that are above. 1. Give a high-level algorithm (using for instance sentences such as flip the three first pancakes ) that correctly orders a stack of pancakes. 2. Give a low-level implementation of you algorithm, using linked lists. 3. Pancakes always have a side that is prettier than the other. Order the stack so that the pretty side is always facing top. INF301 8

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE

DOWNLOAD PDF LINKED LIST PROGRAMS IN DATA STRUCTURE Chapter 1 : What is an application of linear linked list data structures? - Quora A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements

More information

12/30/2013 S. NALINI,AP/CSE

12/30/2013 S. NALINI,AP/CSE 12/30/2013 S. NALINI,AP/CSE 1 UNIT I ITERATIVE AND RECURSIVE ALGORITHMS Iterative Algorithms: Measures of Progress and Loop Invariants-Paradigm Shift: Sequence of Actions versus Sequence of Assertions-

More information

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

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

More information

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING

4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1.2 ALGORITHMS ALGORITHM An Algorithm is a procedure or formula for solving a problem. It is a step-by-step set of operations to be performed. It is almost

More information

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays Unit 3: Linked Lists Part 2: More on Linked Lists 1 Deletion in singly linked lists (cont d) 1 Other Functions Engineering 4892: Data Structures 1 Doubly Linked Lists Faculty of Engineering & Applied Science

More information

CS171 Midterm Exam. October 29, Name:

CS171 Midterm Exam. October 29, Name: CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and

More information

Information Science 2

Information Science 2 Information Science 2 - Basic Data Structures- Week 02 College of Information Science and Engineering Ritsumeikan University Today s class outline l Basic data structures: Definitions and implementation

More information

III Data Structures. Dynamic sets

III Data Structures. Dynamic sets III Data Structures Elementary Data Structures Hash Tables Binary Search Trees Red-Black Trees Dynamic sets Sets are fundamental to computer science Algorithms may require several different types of operations

More information

Basic Data Structures (Version 7) Name:

Basic Data Structures (Version 7) Name: Prerequisite Concepts for Analysis of Algorithms Basic Data Structures (Version 7) Name: Email: Concept: mathematics notation 1. log 2 n is: Code: 21481 (A) o(log 10 n) (B) ω(log 10 n) (C) Θ(log 10 n)

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 02 / 15 / 2016 Instructor: Michael Eckmann Questions? Comments? Loops to repeat code while loops for loops do while loops Today s Topics Logical operators Example

More information

CMSC 341 Lecture 7 Lists

CMSC 341 Lecture 7 Lists CMSC 341 Lecture 7 Lists Today s Topics Linked Lists vs Arrays Nodes Using Linked Lists Supporting Actors (member variables) Overview Creation Traversal Deletion UMBC CMSC 341 Lists 2 Linked Lists vs Arrays

More information

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues

Lists (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues (Section 5) Lists, linked lists Implementation of lists in C Other list structures List implementation of stacks, queues, priority queues By: Pramod Parajuli, Department of Computer Science, St. Xavier

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

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

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

More information

Solved by: Syed Zain Ali Bukhari (BSCS)

Solved by: Syed Zain Ali Bukhari (BSCS) Solved by: Syed Zain Ali Bukhari (BSCS) 1. If there are N internal nodes in a binary tree then what will be the no. of external nodes in this binary tree? N -1 N N +1 (Page 303) N +2 2.If there are N elements

More information

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

The time and space are the two measure for efficiency of an algorithm.

The time and space are the two measure for efficiency of an algorithm. There are basically six operations: 5. Sorting: Arranging the elements of list in an order (either ascending or descending). 6. Merging: combining the two list into one list. Algorithm: The time and space

More information

Graphs. The ultimate data structure. graphs 1

Graphs. The ultimate data structure. graphs 1 Graphs The ultimate data structure graphs 1 Definition of graph Non-linear data structure consisting of nodes & links between them (like trees in this sense) Unlike trees, graph nodes may be completely

More information

CS-301 Data Structure. Tariq Hanif

CS-301 Data Structure. Tariq Hanif 1. The tree data structure is a Linear data structure Non-linear data structure Graphical data structure Data structure like queue FINALTERM EXAMINATION Spring 2012 CS301- Data Structure 25-07-2012 2.

More information

Week 6. Data structures

Week 6. Data structures 1 2 3 4 5 n Week 6 Data structures 6 7 n 8 General remarks We start considering Part III Data Structures from CLRS. As a first example we consider two special of buffers, namely stacks and queues. Reading

More information

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

More information

Pointers, Arrays and Parameters

Pointers, Arrays and Parameters Pointers, Arrays and Parameters This exercise is different from our usual exercises. You don t have so much a problem to solve by creating a program but rather some things to understand about the programming

More information

infix expressions (review)

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

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

CP222 Computer Science II. Searching and Sorting

CP222 Computer Science II. Searching and Sorting CP222 Computer Science II Searching and Sorting New Boston Dynamics wheeled robot Tech News! Tech News! New Boston Dynamics wheeled robot Man charged with arson based on pacemaker data Quiz! How do you

More information

Linked List Nodes (reminder)

Linked List Nodes (reminder) Outline linked lists reminders: nodes, implementation, invariants circular linked list doubly-linked lists iterators the Java foreach statement iterator implementation the ListIterator interface Linked

More information

DDS Dynamic Search Trees

DDS Dynamic Search Trees DDS Dynamic Search Trees 1 Data structures l A data structure models some abstract object. It implements a number of operations on this object, which usually can be classified into l creation and deletion

More information

Static Program Checking

Static Program Checking Bounded Verification Jalloy Automated Software Analysis Group, Institute of Theoretical Informatics Jun.-prof. Mana Taghdiri June 5, 2014 KIT University of the State of Baden-Wuerttemberg and National

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #16 Loops: Matrix Using Nested for Loop In this section, we will use the, for loop to code of the matrix problem.

More information

Insertion Sort: an algorithm for sorting an array

Insertion Sort: an algorithm for sorting an array Insertion Sort: an algorithm for sorting an array Let s use arrays to solve a problem that comes up often in programming, namely sorting. Suppose we have an array of objects that is in no particular order

More information

Algorithms and Data Structures

Algorithms and Data Structures Algorithms and Data Structures PD Dr. rer. nat. habil. Ralf Peter Mundani Computation in Engineering / BGU Scientific Computing in Computer Science / INF Summer Term 2018 Part 2: Data Structures PD Dr.

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #34. Function with pointer Argument Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #34 Function with pointer Argument (Refer Slide Time: 00:05) So, here is the stuff that we have seen about pointers.

More information

Algorithms -RE-S-O-N-A-N-C-E--I-J-~ ~-~ Data Structures: Lists, Queues, Stacks and Arrays

Algorithms -RE-S-O-N-A-N-C-E--I-J-~ ~-~ Data Structures: Lists, Queues, Stacks and Arrays Algorithms 7. Data Structures: Lists, Queues, Stacks and Arrays R K Shyamasundar This article continues with the exploration of common data structures. In particular, we shall discuss representation of

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

Final Exam Data Structure course. No. of Branches (5)

Final Exam Data Structure course. No. of Branches (5) Page ١of 5 College Of Science and Technology Khan younis - Palestine Computer Science & Inf. Tech. Information Technology Data Structure (Theoretical Part) Time: 2 Hours Name: ID: Mark: Teacher 50 Mahmoud

More information

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

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

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Red-black trees (19.5), B-trees (19.8), trees

Red-black trees (19.5), B-trees (19.8), trees Red-black trees (19.5), B-trees (19.8), 2-3-4 trees Red-black trees A red-black tree is a balanced BST It has a more complicated invariant than an AVL tree: Each node is coloured red or black A red node

More information

ITI Introduction to Computing II

ITI Introduction to Computing II index.pdf March 17, 2013 1 ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of March 17, 2013 Definitions A List is a linear abstract

More information

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50 Lists, Stacks, and Queues (Lists, Stacks, and Queues ) Data Structures and Programming Spring 2016 1 / 50 Abstract Data Types (ADT) Data type a set of objects + a set of operations Example: integer set

More information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

More information

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F))

8. Write an example for expression tree. [A/M 10] (A+B)*((C-D)/(E^F)) DHANALAKSHMI COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING EC6301 OBJECT ORIENTED PROGRAMMING AND DATA STRUCTURES UNIT IV NONLINEAR DATA STRUCTURES Part A 1. Define Tree [N/D 08]

More information

In either case, remember to delete each array that you allocate.

In either case, remember to delete each array that you allocate. CS 103 Path-so-logical 1 Introduction In this programming assignment you will write a program to read a given maze (provided as an ASCII text file) and find the shortest path from start to finish. 2 Techniques

More information

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

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

More information

Linked Lists, Stacks, and Queues

Linked Lists, Stacks, and Queues Department of Computer Science and Engineering Chinese University of Hong Kong In a nutshell, a data structure describes how data are stored in memory, in order to facilitate certain operations. In all

More information

Lists. CITS2200 Data Structures and Algorithms. Topic 9

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

More information

3. Fundamental Data Structures

3. Fundamental Data Structures 3. Fundamental Data Structures CH08-320201: Algorithms and Data Structures 233 Data Structures Definition (recall): A data structure is a way to store and organize data in order to facilitate access and

More information

Question 1. Notes on the Exam. Today. Comp 104: Operating Systems Concepts 11/05/2015. Revision Lectures

Question 1. Notes on the Exam. Today. Comp 104: Operating Systems Concepts 11/05/2015. Revision Lectures Comp 104: Operating Systems Concepts Revision Lectures Today Here are a sample of questions that could appear in the exam Please LET ME KNOW if there are particular subjects you want to know about??? 1

More information

Lecture Notes on Priority Queues

Lecture Notes on Priority Queues Lecture Notes on Priority Queues 15-122: Principles of Imperative Computation Frank Pfenning Lecture 16 October 18, 2012 1 Introduction In this lecture we will look at priority queues as an abstract type

More information

Chapter 8 Algorithms 1

Chapter 8 Algorithms 1 Chapter 8 Algorithms 1 Objectives After studying this chapter, the student should be able to: Define an algorithm and relate it to problem solving. Define three construct and describe their use in algorithms.

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

UNINFORMED SEARCH. Announcements Reading Section 3.4, especially 3.4.1, 3.4.2, 3.4.3, 3.4.5

UNINFORMED SEARCH. Announcements Reading Section 3.4, especially 3.4.1, 3.4.2, 3.4.3, 3.4.5 UNINFORMED SEARCH Announcements Reading Section 3.4, especially 3.4.1, 3.4.2, 3.4.3, 3.4.5 Robbie has no idea where room X is, and may have little choice but to try going down this corridor and that. On

More information

WYSE Academic Challenge State Finals Computer Science 2007 Solution Set

WYSE Academic Challenge State Finals Computer Science 2007 Solution Set WYSE Academic Challenge State Finals Computer Science 2007 Solution Set 1. Correct answer: C. a) PGP is for encrypting documents, traditionally used for email. b) SSH is used to gain secure access to a

More information

Memory Management. 3. What two registers can be used to provide a simple form of memory protection? Base register Limit Register

Memory Management. 3. What two registers can be used to provide a simple form of memory protection? Base register Limit Register Memory Management 1. Describe the sequence of instruction-execution life cycle? A typical instruction-execution life cycle: Fetches (load) an instruction from specific memory address. Decode the instruction

More information

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING CMPE13/L: INTRODUCTION TO PROGRAMMING IN C SPRING 2012 Lab 3 Matrix Math Introduction Reading In this lab you will write a

More information

Dictionaries and Hash Tables

Dictionaries and Hash Tables Dictionaries and Hash Tables Nicholas Mainardi Dipartimento di Elettronica e Informazione Politecnico di Milano nicholas.mainardi@polimi.it 14th June 2017 Dictionaries What is a dictionary? A dictionary

More information

Depiction of program declaring a variable and then assigning it a value

Depiction of program declaring a variable and then assigning it a value Programming languages I have found, the easiest first computer language to learn is VBA, the macro programming language provided with Microsoft Office. All examples below, will All modern programming languages

More information

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators)

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators) _ UWNetID: Lecture Section: A CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will give

More information

Unit 8: Analysis of Algorithms 1: Searching

Unit 8: Analysis of Algorithms 1: Searching P Computer Science Unit 8: nalysis of lgorithms 1: Searching Topics: I. Sigma and Big-O notation II. Linear Search III. Binary Search Materials: I. Rawlins 1.6 II. Rawlins 2.1 III. Rawlins 2.3 IV. Sigma

More information

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers)

Notes on the Exam. Question 1. Today. Comp 104:Operating Systems Concepts 11/05/2015. Revision Lectures (separate questions and answers) Comp 104:Operating Systems Concepts Revision Lectures (separate questions and answers) Today Here are a sample of questions that could appear in the exam Please LET ME KNOW if there are particular subjects

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

More information

Linked lists. Insert Delete Lookup Doubly-linked lists. Lecture 6: Linked Lists

Linked lists. Insert Delete Lookup Doubly-linked lists. Lecture 6: Linked Lists Linked lists Insert Delete Lookup Doubly-linked lists Lecture 6: Linked Lists Object References When you declare a variable of a non-primitive type you are really declaring a reference to that object String

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

Create your first workbook

Create your first workbook Create your first workbook You've been asked to enter data in Excel, but you've never worked with Excel. Where do you begin? Or perhaps you have worked in Excel a time or two, but you still wonder how

More information

11 Data Structures Foundations of Computer Science Cengage Learning

11 Data Structures Foundations of Computer Science Cengage Learning 11 Data Structures 11.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define a data structure. Define an array as a data structure

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CSE 230 Intermediate Programming in C and C++

CSE 230 Intermediate Programming in C and C++ CSE 230 Intermediate Programming in C and C++ Structures and List Processing Fall 2017 Stony Brook University Instructor: Shebuti Rayana http://www3.cs.stonybrook.edu/~cse230/ Self-referential Structure

More information

CSED233: Data Structures (2018F) Lecture3: Arrays and Linked Lists

CSED233: Data Structures (2018F) Lecture3: Arrays and Linked Lists (2018F) Lecture3: Arrays and Linked Lists Daijin Kim CSE, POSTECH dkim@postech.ac.kr Array Definition An array is a sequenced collection of variables all of the same type. Each variable, or cell, in an

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop

More information

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers)

Comp 204: Computer Systems and Their Implementation. Lecture 25a: Revision Lectures (separate questions and answers) Comp 204: Computer Systems and Their Implementation Lecture 25a: Revision Lectures (separate questions and answers) 1 Today Here are a sample of questions that could appear in the exam Please LET ME KNOW

More information

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order.

Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Sorting The sorting problem is defined as follows: Sorting: Given a list A with n elements possessing a total order, return a list with the same elements in non-decreasing order. Remember that total order

More information

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department Abstract Data Structures IB Computer Science Content developed by Dartford Grammar School Computer Science Department HL Topics 1-7, D1-4 1: System design 2: Computer Organisation 3: Networks 4: Computational

More information

LIFO : Last In First Out

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

More information

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

Lecture 9 Stacks & Queues

Lecture 9 Stacks & Queues Lecture 9 Stacks & Queues 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning, André Platzer, Rob Simmons In this lecture we introduce queues and stacks as data structures, e.g., for

More information

CS 216 Exam 1 Fall SOLUTION

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

More information

Fundamentals of Operations Research. Prof. G. Srinivasan. Department of Management Studies. Indian Institute of Technology Madras.

Fundamentals of Operations Research. Prof. G. Srinivasan. Department of Management Studies. Indian Institute of Technology Madras. Fundamentals of Operations Research Prof. G. Srinivasan Department of Management Studies Indian Institute of Technology Madras Lecture No # 06 Simplex Algorithm Initialization and Iteration (Refer Slide

More information

DATA STRUCTURE AND ALGORITHM USING PYTHON

DATA STRUCTURE AND ALGORITHM USING PYTHON DATA STRUCTURE AND ALGORITHM USING PYTHON Advanced Data Structure and File Manipulation Peter Lo Linear Structure Queue, Stack, Linked List and Tree 2 Queue A queue is a line of people or things waiting

More information

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5

C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5 C PROGRAMMING LANGUAGE. POINTERS, ARRAYS, OPERATORS AND LOOP. CAAM 519, CHAPTER5 1. Pointers As Kernighan and Ritchie state, a pointer is a variable that contains the address of a variable. They have been

More information

CS-141 Exam 2 Review April 4, 2015 Presented by the RIT Computer Science Community

CS-141 Exam 2 Review April 4, 2015 Presented by the RIT Computer Science Community CS-141 Exam 2 Review April 4, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu Linked Lists 1. You are given the linked list: 1 2 3. You may assume that each node has one field

More information

Positional Sequences Section 4.2

Positional Sequences Section 4.2 Positional Sequences Section 4.2 PS-1 Problem with Ranked Sequences Problem with ranked sequences» rank of a particular element may change as other elements are inserted and deleted For example if you

More information

Data Structure. Recitation III

Data Structure. Recitation III Data Structure Recitation III Topic Binary Search Abstract Data types Java Interface Linked List Binary search Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions.

More information

811312A Data Structures and Algorithms, , Exercise 1 Solutions

811312A Data Structures and Algorithms, , Exercise 1 Solutions 811312A Data Structures and Algorithms, 2018-2019, Exercise 1 Solutions Topics of this exercise are stacks, queues, and s. Cormen 3 rd edition, chapter 10. Task 1.1 Assume that L is a containing 1000 items.

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

COMP 250 Midterm #2 March 11 th 2013

COMP 250 Midterm #2 March 11 th 2013 NAME: STUDENT ID: COMP 250 Midterm #2 March 11 th 2013 - This exam has 6 pages - This is an open book and open notes exam. No electronic equipment is allowed. 1) Questions with short answers (28 points;

More information

Global Optimization. Lecture Outline. Global flow analysis. Global constant propagation. Liveness analysis. Local Optimization. Global Optimization

Global Optimization. Lecture Outline. Global flow analysis. Global constant propagation. Liveness analysis. Local Optimization. Global Optimization Lecture Outline Global Optimization Global flow analysis Global constant propagation Liveness analysis Compiler Design I (2011) 2 Local Optimization Recall the simple basic-block optimizations Constant

More information

Unit 10: Data Structures CS 101, Fall 2018

Unit 10: Data Structures CS 101, Fall 2018 Unit 10: Data Structures CS 101, Fall 2018 Learning Objectives After completing this unit, you should be able to: Define and give everyday examples of arrays, stacks, queues, and trees. Explain what a

More information

Problem Set 8 Solutions

Problem Set 8 Solutions Introduction to Algorithms November 22, 25 Massachusetts Institute of Technology 6.46J/8.4J Professors Erik D. Demaine and Charles E. Leiserson Handout 27 Problem Set 8 Solutions Problem 8-. No left turns

More information

Ashish Gupta, Data JUET, Guna

Ashish Gupta, Data JUET, Guna Categories of data structures Data structures are categories in two classes 1. Linear data structure: - organized into sequential fashion - elements are attached one after another - easy to implement because

More information

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University CS 112 Introduction to Computing II Wayne Snyder Department Boston University Today Introduction to Linked Lists Stacks and Queues using Linked Lists Next Time Iterative Algorithms on Linked Lists Reading:

More information

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

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

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

(Python) Chapter 3: Repetition

(Python) Chapter 3: Repetition (Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the

More information

ProCo 2017 Novice Division Round 1

ProCo 2017 Novice Division Round 1 ProCo 017 Novice Division Round 1 Problem A. How far you ll go file: 64 megabytes Before you embark on this journey to help Moana, you should write some words of encouragement to yourself. None Print a

More information