Chapter 3 Linear List (Sequential List)

Slides:



Advertisements
Similar presentations
Linear Lists – Array Representation
Advertisements

DATA STRUCTURES USING C++ Chapter 5
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Chapter 3 – Lists A list is just what the name implies, a finite, ordered sequence of items. Order indicates each item has a position. A list of size 0.
Array pair C++ array requires the index set to be a set of consecutive integers starting at 0 C++ does not check an array index to ensure that it belongs.
Data Abstraction and Encapsulation
Chapter 2. C++ Class A class name Data members Member functions Levels of program access –Public: section of a class can be accessed by anyone –Private:
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 17 Linked.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Writing Your Own STL Container Ray Lischner
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data Structure (Part I) Chapter 2 – Arrays Data Abstraction and Encapsulation in C++ Section 1.3 –Data Encapsulation Also called information hiding.
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Containers Overview and Class Vector
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
CPSC 252 Concrete Data Types Page 1 Overview of Concrete Data Types There are two kinds of data types: Simple (or atomic) – represents a single data item.
Pointers OVERVIEW.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Lecture 7 : Intro. to STL (Standard Template Library)
Linked List (Part I). Introduction  Weakness of storing an ordered list in array: Insertion and deletion of arbitrary elements are expensive. ○ Example:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
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 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
114 3/30/98 CSE 143 Collection ADTs [Chapter 4] /30/98 Collection ADTs  Many standard ADTs are for collections  Data structures that manage groups.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
LINKED LISTS.
Standard Template Library
CS212: Object Oriented Analysis and Design
Chapter 4 The easy stuff.
Standard Template Library
Linked Lists Chapter 6 Section 6.4 – 6.6
Lists CS 3358.
Standard Template Library (STL)
CSCE 210 Data Structures and Algorithms
Lecture 4 Linked List and STL
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Chapter 18: Linked Lists.
Linked List (Part I) Data structure.
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Chapter 16 Linked Structures
Lists - I The List ADT.
Lists - I The List ADT.
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Dynamic allocation (continued)
the Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Chapter 3 Linear List (Sequential List) Lecture-03 Lecture Notes: Data Structures and Algorithms Chapter 3 Linear List (Sequential List) Prof. Qing Wang

Table of Contents Arrays and ADTs of Array Sequential List 1D array ADT of array 2D and high dimensional arrays Sequential List ADT of sequential list Applications Polynomial ADT and Representation Polynomial ADT Sequential Representation of PolyN Addition of Polynomial Prof. Q.Wang

3.1 Arrays and ADTs One dimensional array An example Prof. Q.Wang

Arrays and ADTs Characteristics of one dimensional array In contiguous storage, also called as Vector Except the first element of an array, other elements have and only have one predecessor Except the last element of the array, other elements have and only have one successor First element Last element Prof. Q.Wang

ADT of 1D Array (Class Definition) #include <iostream.h> #include <stdlib.h> template <class Type> class Array { private: Type *elements; // Space to store array int ArraySize; // Length of array void getArray ( ); // Initialization of storage for array public: Array( int Size=DefaultSize ); // Constructor Array( const Array<Type>& x ); // Constructor (copy) Prof. Q.Wang

~Array( ) { delete [ ]elements;} //Deconstructor Array <Type> & operator = // Array duplication ( const Array <Type> & A ); Type& operator [ ] ( int i ); // Get the element of the array Type* operator ( ) const // Conversion of the pointers { return elements; } int Length ( ) const // Get the length of array { return ArraySize; } void ReSize ( int sz ); // Enlarge the size of the array } Prof. Q.Wang

Implementation of Methods for 1D Array Memory allocation template <class Type> void Array <Type>::getArray ( ) { // Private Function: Allocate the space for the array elements = new Type[ArraySize]; if ( elements == 0 ) { arraySize = 0; cerr << "Memory Allocation Error" << endl; return; } Prof. Q.Wang

Implementation of Methods for 1D Array Constructor template <class Type> Array <Type>::Array ( int sz ) { // Constructor Function of Array ADT if ( sz <= 0 ) { arraySize = 0; cerr << “Invalid size of array!” << endl; return; } ArraySize = sz; getArray ( ); Prof. Q.Wang

Implementation of Methods for 1D Array Copy Constructor template <class Type> Array<Type>:: Array ( const Array<Type> & x ) { // Constructor Function (with copy) of Array ADT int n = ArraySize = x.ArraySize; elements = new Type[n]; if ( elements == 0 ) { arraySize = 0; cerr << “Error of Memory Allocation” << endl; return; } Type *srcptr = x.elements; Type *destptr = elements; while ( n-- ) * destptr++ = * srcptr++; Prof. Q.Wang

Implementation of Methods for 1D Array operator [] template <class Type> Type & Array<Type>::operator [ ] ( int i ) { // Get the i-th element of array of Array ADT if ( i < 0 || i > ArraySize-1 ) { cerr << “The i is exceed the bound of the array” << endl; return NULL; } return element[i]; Prof. Q.Wang

Implementation of Methods for 1D Array Resize template <class Type> void Array<Type>::Resize (int sz) { if ( sz >= 0 && sz != ArraySize ) { Type * newarray = new Type[sz]; if ( newarray == 0 ) { cerr << “Error of Memory Allocation” << endl; return; } int n = ( sz <= ArraySize ) ? sz : ArraySize; Prof. Q.Wang

Type *srcptr = elements; Type *destptr = newarray; while ( n-- ) * destptr++ = * srcptr++; delete [ ] elements; elements = newarray; ArraySize = sz; } 2D Array Prof. Q.Wang

2D Array Row subscript i, Column subscript j Prof. Q.Wang

3D Array Page subscript i , Row subscript j , Column subscript k Prof. Q.Wang

Sequential Storage of Arrays 1D array LOC ( i ) = LOC ( i -1 ) + l =α+ i*l Prof. Q.Wang

Sequential Storage of Arrays 2D array Row-first: LOC ( j, k ) = a + ( j * m + k ) * l Prof. Q.Wang

Sequential Storage of Arrays N-D array The dimensions are m1, m2, m3, …, mn The element with subscripts (i1, i2, i3, …, in) is in the space: LOC ( i1, i2, …, in ) = a + ( i1*m2*m3*…*mn + i2*m3*m4*…*mn+ + ……+ in-1*mn + in ) * l Sequential List Prof. Q.Wang

3.2 Sequential List (Sequence) Definition and Property of Sequential List Definition: A list is a finite, ordered sequence of data items (a1, a2, …, an) where a1 is the item or element of list , n is the length of the list Property: sequential access (put and get) Important concept: List element has a position. Traversal: from the first to the last from the last to the first from the intermediate position to the head or the end Prof. Q.Wang

ADT of Sequential List (Class Definition) template <class Type> class SeqList { private: Type *data; // Array to store the sequential list int MaxSize; // Maximize the size of list int last; // Length of the list public: SeqList ( int MaxSize = defaultSize ); ~SeqList ( ) { delete [ ] data; } int Length ( ) const { return last+1; } int Find ( Type & x ) const; Prof. Q.Wang

int Insert ( Type & x, int i ); int Remove ( Type & x ); int IsIn ( Type & x ); int Insert ( Type & x, int i ); int Remove ( Type & x ); int Next ( Type & x ) ; int Prior ( Type & x ) ; int IsEmpty ( ) { return last ==-1; } int IsFull ( ) { return last == MaxSize-1; } Type Get ( int i ) { return i < 0 || i > last?NULL : data[i]; } Prof. Q.Wang

Implementation of Methods for Sequential List template <class Type> SeqList<Type> :: SeqList ( int sz ) { // Constructor Function if ( sz > 0 ) { MaxSize = sz; last = -1; data = new Type[MaxSize]; if ( data == NULL ) { MaxSize = 0; last = -1; return; } Find Prof. Q.Wang

Implementation of Methods for Sequential List template <class Type> int SeqList<Type>::Find ( Type & x ) const { // Searching Function: try to find out the position of x int i = 0; while ( i <= last && data[i] != x ) i++; if ( i > last ) return -1; else return i; } Prof. Q.Wang

Details of Searching in the List Prof. Q.Wang

Complexity Analysis of Searching If success Average Comparison Number (ACN) is If fail to search x, Actual comparison number is n Insert element Prof. Q.Wang

Insert an item into the List Average Move Number (AMN) is Prof. Q.Wang

Insert an item into the List template <class Type> int SeqList<Type>::Insert ( Type & x, int i ){ // Insert a new item with (x) before pos i in the list if ( i < 0 || i > last+1 || last == MaxSize-1 ) return 0; // Fail to insert else { last++; for ( int j = last; j > i; j-- ) // Move elements data[j] = data[j -1]; data[i] = x; return 1; // Success to insert } Remove element Prof. Q.Wang

Remove an item from the List Average Move Number (AMN) is Prof. Q.Wang

Remove an item from the List template <class Type> int SeqList<Type>::Remove ( Type & x ) { // Remove existed item x from the list int i = Find (x); // Search x in the list if ( i >= 0 ) { last-- ; for ( int j = i; j <= last; j++ ) data[j] = data[j+1]; // Move elements return 1; // Success to remove x } return 0; // No removal if no item x Application Prof. Q.Wang

Application of Sequential List (1) Union of two sets a2 b2 a1 b1 an bm ai bi a1, a2, …,ai… an, b1, b2, …, bi… bm, N Insert Get an item bi Get another item Y Prof. Q.Wang

Union of two sets template <class Type> void Union ( SeqList<Type> & LA, SeqList<Type> & LB ) { int n = LA.Length ( ); int m = LB.Length ( ); for ( int i = 1; i <= m; i++ ) { Type x = LB.Get(i); // Get an item x from Set LB int k = LA.Find (x); // Search x in Set LA if ( k == -1 ) // if not found, insert x into LA { LA.Insert (x, n+1); n++; } } Prof. Q.Wang

Application of Sequential List (2) Intersection of two sets b2 a2 b1 a1 bm an bi ai Remove from A a1, a2, …,ai… an, Y Get an item ai Get another item N Prof. Q.Wang

Intersection of two sets template <class Type> void Intersection ( SeqList<Type> & LA, SeqList<Type> & LB ) { int n = LA.Length ( ); int m = LB.Length ( ); int i = 0; while ( i < n ) { Type x = LA.Get (i); // Get an item x from LA int k = LB.Find (x); // Search x in Set LB if ( k == -1 ) { LA.Remove (i); n--; } else i++; // if not found, remove x from LA } Prof. Q.Wang

Application of Sequential List (3) Merge two sorted lists into a new list and the new one is also sorted as before. i LA= (3, 5, 8, 11) LB= (2, 6, 8, 9, 11, 15, 20) j LC= (2, 3, 5, 6, 8, 8, 9, 11, 11, 15, 20) Merge k Prof. Q.Wang

Application of Sequential List (3) Implementation template <class Type> SeqList &Merge_List ( SeqList <Type> & LA, SeqList <Type> & LB ) { int n = LA.Length ( ); int m = LB.Length ( ); SeqList LC(m+n); int i=j=k=0; while ( i < n && j<m) { Type x = LA.Get (i); // Get an item x from LA Type y = LB.Get (j); // Get an item y from LB Prof. Q.Wang

{ LC.Insert (k, x); i++; k++;} // Insert x into LC else if (x <= y ) { LC.Insert (k, x); i++; k++;} // Insert x into LC else { LC.Insert (k, y); j++; k++;} } while ( i < n) { // Insert the remains of LA into LC Type x = LA.Get (i); LC.Insert (k, x); i++; k++; while (j<m) { // Insert the remains of LB into LC Type y = LB.Get (j); LC.Insert (k, y); j++; k++; return LC; Prof. Q.Wang

3.3 Polynomial N-order polynomial Pn(x) has n+1 items。 Coefficients: a0, a1, a2, …, an Exponentials: 0, 1, 2, …, n。 ascending Prof. Q.Wang

Polynomial ( ); //Constructor int operator ! ( ); //Is zero-polynomial ADT of Polynomial class Polynomial { public: Polynomial ( ); //Constructor int operator ! ( ); //Is zero-polynomial float Coef ( int e); int LeadExp ( ); //return max-exp Polynomial Add (Polynomial poly); Polynomial Mult (Polynomial poly); float Eval ( float x); //compute the value of the PN } Prof. Q.Wang

To computer the power of x, (Power Class) #include <iostream.h> class power { double x; int e; double mul; //The value of ex public: power (double val, int exp); //constructor double get_power ( ) { return mul; } //Get ex }; Prof. Q.Wang

power::power (double val, int exp) { //Computer the power of val xe x = val; e = exp; mul = 1.0; if ( exp == 0 ) return; for ( ; exp>0; exp--) mul = mul * x; } main ( ) { power pwr ( 1.5, 2 ); cout << pwr.get_power ( ) << “\n”; Prof. Q.Wang

Representation of Polynomial (storage) 1st method: private: int degree; float coef [maxDegree+1]; Pn(x): pl.degree = n pl.coef[i] = ai, 0  i  n Prof. Q.Wang

Polynomial::Polynomial (int sz) { degree = sz; 2nd method: private: int degree; float * coef; Polynomial::Polynomial (int sz) { degree = sz; coef = new float [degree + 1]; } The 1st and 2nd storages are NOT suitable for the following case P101(x) = 3 + 5x50 - 14x101 Prof. Q.Wang

class term { //item definition 3rd method: class Polynomial; class term { //item definition friend Polynomial; //PN class is the friend class of item class private: float coef; //coefficient int exp; //exponential }; Prof. Q.Wang

class Polynomial { //Polynomial class public: …… private: static term termArray[MaxTerms]; //items static int free; //pos of current free space // term Polynomial::termArray[MaxTerms]; // int Polynomial::free = 0; int start, finish; //start and finish pos of the items of //Polynomial } Prof. Q.Wang

A(x) = 2.0x1000+1.8 Two polynomials are stored in termArray Examples: Two polynomials are stored in termArray A(x) = 2.0x1000+1.8 B(x) = 1.2 + 51.3x50 + 3.7x101 Prof. Q.Wang

Addition of Polynomials Requirement The summarization polynomial is an new one Method To traverse two polynomials (A and B) until one of them has been traversed; If the exps are equal, add two coefs. If the addition of coefs are not equal to 0, new a item and append it into C, otherwise continue to traverse. If the exps are not equal, add the item whose exp is lower into C. If one of A and B has been traversed completely, it is easy to duplicate the remains of another one into C Prof. Q.Wang

Polynomial Polynomial::Add (Polynomial B) { Polynomial C; int a = start; int b = B.start; C.start = free; float c; while ( a <= finish && b <= B.finish ) Switch ( compare ( termArray[a].exp, termArray[b].exp) ) { //compare case ‘=’ : //exps are equal c = termArray[a].coef + //coef termArray[b].coef; if ( c ) NewTerm ( c, termArray[a].exp ); a++; b++; break; Prof. Q.Wang

for ( ; b <= B.finish; b++ ) //B has remains case ‘>’ : // new item with item b in C NewTerm ( termArray[b].coef, termArray[b].exp ); b++; break; case '<': // new item with item a in C NewTerm ( termArray[a].coef, termArray[a].exp ); a++; } for ( ; a <= finish; a++ ) //A has remains for ( ; b <= B.finish; b++ ) //B has remains C.finish = free-1; return C; Prof. Q.Wang

Add a new item in the polynomial void Polynomial::NewTerm ( float c, int e ) { // Add a new item into polynomial if ( free >= maxTerms ) { cout << "Too many terms in polynomials” << endl; return; } termArray[free].coef = c; termArray[free].exp = e; free++; Prof. Q.Wang

Points of Chapter 3 Array Sequential List Polynomial ADT of array Methods Sequential List ADT Applications Polynomial ADT and Representation Addition STL Prof. Q.Wang

Standard Template Library STL Overview Standard Template Library Dr. Qing Wang

Introduction to the Standard Template Library STL Overview Containers Iterators Algorithms STL Overview Prof. Q.Wang

STL Overview The library is organized into three main abstractions Containers Iterators Algorithms Prof. Q.Wang

Detail of containers The containers include strings, vectors, lists, sets, stacks, and the like. The containers are organized as a collection of independent C++ classes. All the STL containers classes are template classes. Prof. Q.Wang

Containers Prof. Q.Wang

Iterators Iterators provide a uniform interface between containers and algorithms in the STL. Iterators are modeled after plain C++ pointers. In particular, operators operator*, operator++ and so forth are properly overloaded, so that the use of iterators is very similar to the use of pointers. Prof. Q.Wang

Iterators Prof. Q.Wang

Algorithms The core of the STL is its extensive collection of algorithms. Insertion Removal Retrieval Modification Traversal Replacement Sorting …… Prof. Q.Wang

Example of Algorithms Prof. Q.Wang

A Tour of the Standard Library C++reference C++ Reference A Tour of the Standard Library C++ glossary Sequential List using STL Prof. Q.Wang

Implementation of Sequential List using STL Dr. Qing Wang

Contents String Array STL sequence containers Vector Deque Prof. Q.Wang

Using the Standard string Class C-style Strings The standard string class provides support for character strings. String class provides ease of use, convenience, and safety that C-style strings lack. Prof. Q.Wang

Using the Standard string Class Prof. Q.Wang

Using the Standard string Class Advanced String Operations Prof. Q.Wang

Using the Standard string Class In C++, the string data type provides the necessary abstraction to allow C++ programmers to work with character strings. C++ string Ref Prof. Q.Wang

Array C++ provides basic support for a sequence of homogeneous data objects through arrays. Prof. Q.Wang

Example Prof. Q.Wang

Using the Standard vector Class Vector as an Array Class More safer than array Templates supported Prof. Q.Wang

Using the Standard vector Class declare a vector of vector objects an implementation for a two-dimensional data structure such as a matrix. Prof. Q.Wang

Using the Standard vector Class Constructor Prof. Q.Wang

Using the Standard vector Class Element access Other member functions Prof. Q.Wang

Using the Standard vector Class Vector as an STL Container As an STL container, class vector provides access to its elements via iterators. Iterators allow interoperability of vector objects and the STL algorithms. Prof. Q.Wang

Using the Standard vector Class Iterators return iterators to the invoking vector. begin returns an iterator to the first element in the vector end returns an iterator positioned beyond the last element in the vector Reverse iterators Prof. Q.Wang

Using the Standard vector Class Insert and erase functions Take vector iterators as parameters. These iterators indicate the location to insert, or the elements to erase. Prof. Q.Wang

Using the Standard vector Class C++ Vectors Vectors contain contiguous elements stored as an array. Accessing members of a vector or appending elements can be done in constant time, whereas locating a specific value or inserting elements into the vector takes linear time. C++ vector Ref Prof. Q.Wang

Using the STL deque Container Double-ended Queue Interface can store and provide access to a linear sequence of elements C++ deque Ref Prof. Q.Wang

STL deque push_front and pop_front Prof. Q.Wang

STL deque count and count_if functions: Counting the number of items that possess certain properties Prof. Q.Wang

Difference between vector and deque Storage strategies Vectors reserve memory only at the rear of stored elements Deques reserve memory locations at both the front and rear of their stored elements Prof. Q.Wang

Difference between vector and deque Operations The same ones push_back pop_back For deque only push_front pop_front For vector Alternative method: insert or erase the first element Prof. Q.Wang

Summary Containers Iterators Algorithms Sequences Vector Deque Prof. Q.Wang

Quiz Quiz1 Prof. Q.Wang