Lists. Container Classes Many applications in Computer Science require the storage of information for collections of entities e.g. a student registration.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
CSE Lecture 12 – Linked Lists …
COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
Data Structure Dr. Mohamed Khafagy.
Queue Overview Queue ADT Basic operations of queue
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
1 Problem Solving Abstraction Oftentimes, different real-world problems can be modeled using the same underlying idea Examples: Runtime storage, Undo operation.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Typical operations on data –Add data.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Computer Science 1620 Programming & Problem Solving.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Introduction - The Need for Data Structures Data structures organize data –This gives more efficient programs. More powerful computers encourage more complex.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 6 Vectors and arrays: Arrays: Run the following code. Anything unusual? #include using namespace std; #define N 10 #define M 11 int main() { int.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Comp 335 File Structures Hashing.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Pointers OVERVIEW.
CSC 211 Data Structures Lecture 13
Lists II. List ADT When using an array-based implementation of the List ADT we encounter two problems; 1. Overflow 2. Wasted Space These limitations are.
A first look an ADTs Solving a problem involves processing data, and an important part of the solution is the careful organization of the data In order.
Data Structures and Algorithms Lecture 1 Instructor: Quratulain Date: 1 st Sep, 2009.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Data Structures & Algorithms
CPSC 252 Hashing Page 1 Hashing We have already seen that we can search for a key item in an array using either linear or binary search. It would be better.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
Queues Chapter 5 Queue Definition A queue is an ordered collection of data items such that: –Items can be removed only at one end (the front of the queue)
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Chapter Lists Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2010.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Chapter 6 Methods for Making Data Structures. 2 Dynamic Arrays in Data Structures In almost every data structure, we want functions for inserting and.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
1 CSC 211 Data Structures Lecture 11 Dr. Iftikhar Azim Niaz 1.
Data Structures AZHAR MAQSOOD NUST Institute of Information Technology (NIIT) Lecture 6: Linked Lists Linked List Basics.
Array 10 GB Hard Disk 2 GB 4 GB2 GB 3 GB DATA 4 GB Free Store data in the form of Array (Continuous memory locations) Solution-1: No Solution. Memory Insufficient.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
CHAPTER 51 LINKED LISTS. Introduction link list is a linear array collection of data elements called nodes, where the linear order is given by means of.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Computer Skills2 / Scientific Colleges 1 Arrays Topics to cover: Arrays Data Types One-dimensional Arrays Two-dimensional Arrays.
1 Data Organization Example 1: Heap storage management Maintain a sequence of free chunks of memory Find an appropriate chunk when allocation is requested.
Review Array Array Elements Accessing array elements
Chapter 4 The easy stuff.
Lists CS 3358.
Data Abstraction: The Walls
Queues Queues Queues.
Pointers and Dynamic Variables
Introduction to Linked Lists
Introduction to C++ Programming
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Introduction to Data Structure
Lists.
Presentation transcript:

Lists

Container Classes Many applications in Computer Science require the storage of information for collections of entities e.g. a student registration program will store records for students, a payroll system will store records for employees etc. Computer Scientists have developed many techniques over the years for storing collections of data. These storage structures are known as containers. For the remainder of the course we will study some commonly used containers in Computer Science along with their implementation in an OOP language.

Lists The List ADT The list is probably the simplest container type used to store collections of data. Its specification is as follows: A list L of type T is a finite sequence of elements of type T, with the following operations defined on it: Test whether L is empty; Test whether L is empty; Determine the length of L (or the number of elements in L); Determine the length of L (or the number of elements in L); Insert an element e at position p in List L; Insert an element e at position p in List L; Find the position of an element e in List L; Find the position of an element e in List L; Retrieve the element at position p in List L; Retrieve the element at position p in List L; Delete an element e from L; Delete an element e from L; Traverse L, applying an operation to each element in L. Traverse L, applying an operation to each element in L.

Lists Since a list is a finite sequence of elements it makes sense to identify each element with a position in the list. This is different from a set of objects where no position is associated with each object. We will also assume that the first position in the list is identified as position 0. This follows the convention for labelling array elements in C and C++.

Lists Some of the behaviours in the List ADT can be specified quite trivially. The following behaviours are more complicated to specify; Insert Insert Locate Locate Delete Delete Traverse Traverse

Lists insert Input: Element e, Position p. Process: IF (p > length() + 1) THEN PRINT("Error. Inserting beyond end of List") ELSE { Move all elements between p and the end of the list up i.e., to next position in list. } { Make e the element at position p. } { Increment the length. } ENDIF Output: None insert Input: Element e, Position p. Process: IF (p > length() + 1) THEN PRINT("Error. Inserting beyond end of List") ELSE { Move all elements between p and the end of the list up i.e., to next position in list. } { Make e the element at position p. } { Increment the length. } ENDIF Output: None

Lists Locate Input: Element e Process: { Note that, if the first position in the list is position 1, rather than position 0, we would have had to initialize the index to 1, rather than 0 } index  0 WHILE (index < length() AND element at index != e) index <- index + 1 ENDWHILE IF (index = length()) THEN PRINT("Error. Element did not occur in List") RETURN –1 ELSE RETURN index ENDIF Output: position of e in list or –1 if e does not occur in list

Lists delete Input: Element e Process: pos <- locate(e) IF (pos = -1) THEN { Notice that the locate has already printed an error message. The current message is therefore not strictly necessary ) PRINT("Error. Could not delete element") ELSE { Move all elements between end if list and pos + 1 to one before the position where they were } { Decrease the size by 1 } ENDIF Output: None

Lists traverse Input: Operation O Process: index <- 0 WHILE(index < length()) { Apply O to the element at index } { Store the result at index } index <- index + 1 ENDWHILE Output: None

Lists Most applications that maintain information about collections of entities usually require that one be able to apply a single operation to all the entities in the collection e.g. all employees in a payroll system may be given a bonus on their salary all accounts in a banking system may have interest calculated on them at the end of each month. The traverse operation is implemented to perform this function. The input to the function is an operation which is applied to all objects in the list.

Lists Array-Based List Implementations Now that the List ADT has been specified there are many ways in which it can be implemented in a programming language. The easiest implementation is probably an implementation based on arrays. When we create a list we declare an array of fixed size. We can then implement the List ADT operations using array elements e.g. if we insert an element at position p, we move all the elements at position p and above up one ( assuming there is space ) and insert the new element in the free array location.

Lists Some Examples An empty list Inserting numbers into the first three positions

Lists Now insert 5.4 in position Insert value in position 1 Move elements up

Lists Deleting Remove 56.7 and shift elements down Locate element

Lists List Termination How does one know where the array-based list terminates ? ( remember all array elements will contain values initially – usually garbage ) There are two possible solutions to the problem; 1. Use a dummy value to indicate the end of the list e.g dummy value

Lists 2. Keep a length attribute that stores the current length of the list. Both methods are valid means of determining the length of a list although both will generate different implementations end=3

Lists No matter what method we use there are some problems associated with array-based list implementations particularly that of overflow and wasted space. Due to the nature of arrays when implemented in a programming language we always need to specify their maximum size. Arrays cannot be dynamically created and therefore we have problems when we run out of array space and are required to add new elements – overflow. On the other hand if we declare large arrays and only use a fraction of the space then we are wasting valuable memory resources.

Lists Array-based List implementation ( using dummy value for end of list ) Assume the list stores positive floating point numbers and the label DUMMY is defined as -1 to record the end of the list. The class declaration is as follows: class List class List { private: float elements[SIZE]; public: List(); Bool empty(); int length(); void insert(float, int); int find(float); float retrieve(int); void del(float); void traverse(float(*op)(float)); };

Lists The traverse() notation void traverse(float(*op)(float)); void traverse(float(*op)(float)); tells the system to expect an operation *op that takes a float as an input and returns a float as output. If L is a pointer to a list and print() has been defined as a function that prints out a float and returns that number then the traverse() function can be used as follows; L->traverse(print);

Lists where print() is specified as: float print(float f) { cout << f << endl; return f; } Now that the class is declared we can specify its behaviour.

Lists /* To create a list, we simply put the DUMMY element in the first position in the list. */ List::List(){ elements[0] = DUMMY; } Bool List::empty() { if ( elements[0] == DUMMY ) return true; else return false; }

Lists /* To determine the length of the list, we look at all elements in the list until we either find the DUMMY element, or we reach the end of the array of the elements making up the array */ int List::length() { int i = 0; while(elements[i] != DUMMY && i < SIZE) i++; return i; }

Lists void List::insert(float e, int pos) { int i = 0; /* First go to the end of the list */ while(elements[i] != DUMMY && i i) cout i) cout << "Error. Beyond end of list." << endl; else

Lists { /* Note that i must be pointing to the DUMMY element. We now shift all elements between the end of the list and the position in which the new element is to be inserted one down. However, we must be careful not to fall of the end of the array. If the DUMMY element was in the last position in the array, we cannot shift it as we would try to shift it beyond the end of the array. In this case we therefore first go one position back. */ if (i == (SIZE - 1)) i--; for(; i >= pos; i--) elements[i + 1] = elements[i]; /* Now insert the new element */ elements[pos] = e; } }

Lists int List::find(float e) { /* We initialize the return value ret to -1. It only gets changed, when we actually find the element we are looking for. In other words, if the element does not occur in the list, we return position -1 */ int i = 0, ret = -1; while(elements[i] != DUMMY && i < SIZE) { if (elements[i] == e) { ret = i; break; } else i++; } int List::find(float e) { /* We initialize the return value ret to -1. It only gets changed, when we actually find the element we are looking for. In other words, if the element does not occur in the list, we return position -1 */ int i = 0, ret = -1; while(elements[i] != DUMMY && i < SIZE) { if (elements[i] == e) { ret = i; break; } else i++; }

Lists if (ret == -1) cout << "Error. Element not in list." << endl; return ret; } if (ret == -1) cout << "Error. Element not in list." << endl; return ret; }

Lists float List::retrieve(int pos) { int i = 0; /* First determine whether the position is actually a legal position. So, we go down the list until we either reach the position, the DUMMY element or the end of the list */ while(elements[i] != DUMMY && i < pos && i < SIZE) i++; if (elements[i] == DUMMY || i == SIZE) { cout << "Error. Illegal position." << endl; return DUMMY; } else return elements[pos]; } float List::retrieve(int pos) { int i = 0; /* First determine whether the position is actually a legal position. So, we go down the list until we either reach the position, the DUMMY element or the end of the list */ while(elements[i] != DUMMY && i < pos && i < SIZE) i++; if (elements[i] == DUMMY || i == SIZE) { cout << "Error. Illegal position." << endl; return DUMMY; } else return elements[pos]; }

Lists void List::del(float e) { int i = 0; /* We go down the list until we find the element */ while(elements[i] != DUMMY && i < SIZE) if (elements[i] == e) break; else i++; if (elements[i] == DUMMY || i == SIZE) cout << "Error. Element not in list." << endl; else void List::del(float e) { int i = 0; /* We go down the list until we find the element */ while(elements[i] != DUMMY && i < SIZE) if (elements[i] == e) break; else i++; if (elements[i] == DUMMY || i == SIZE) cout << "Error. Element not in list." << endl; else

Lists { /* We move all elements one down */ while(elements[i + 1] != DUMMY && ((i + 1) < SIZE)) { elements[i] = elements[i + 1]; i++; } /* Now re-insert the DUMMY */ elements[i] = DUMMY; } } { /* We move all elements one down */ while(elements[i + 1] != DUMMY && ((i + 1) < SIZE)) { elements[i] = elements[i + 1]; i++; } /* Now re-insert the DUMMY */ elements[i] = DUMMY; } }

Lists void List::traverse(float (*f)(float)) { int i = 0; while(elements[i] != DUMMY && i < SIZE) { elements[i] = (*f)(elements[i]); i++; } } Apply the operation *f to an element and store the new element in the array.