A Generic List Class and Linked Lists Andy Wang Data Structures, Algorithms, and Generic Programming.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
DATA STRUCTURES USING C++ Chapter 5
Main Index Contents 11 Main Index Contents Shifting blocks of elements… Shifting blocks of elements… Model of a list object… Model of a list object… Sample.
Lists: An internal look
CSE Lecture 12 – Linked Lists …
LINKED QUEUES P LINKED QUEUE OBJECT Introduction Introduction again, the problem with the previous example of queues is that we are working.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Pointers and Dynamic Objects Mechanisms for developing flexible list representations.
Reviews for Exam 1 Chapter 1-4 CS 211 Data Structures MHC, 2007.
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
1 Queues CPS212 Gordon College. 2 Introduction to Queues A queue is a waiting line – seen in daily life –Real world examples – toll booths, bank, food.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Data Structures Using C++ 2E
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.
1 Joe Meehean.  Conceptual Picture N items chained together using pointers pointed to by head variable  Advantage allows list to grow indefinitely without.
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Generic Positional Containers and Double-Ended Queues.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Pointers and Dynamic Objects Mechanisms for developing flexible list representations JPC and JWD © 2002 McGraw-Hill, Inc.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Section 3.5, class notes Iterators Generic algorithms.
J. P. Cohoon and J. W. Davidson © 1997 McGraw-Hill, Inc. Templates Generic functions and classes.
1 Inside the Vector Class: with additional needed methods CPS212CPS212 Gordon College.
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
1 Working with Pointers An exercise in destroying your computer.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Sets and Maps Andy Wang Data Structures, Algorithms, and Generic Programming.
Copyright © 2002 Pearson Education, Inc. Slide 1.
A Doubly Linked List prevnextdata There’s the need to access a list in reverse order header dnode.
ITERATORS. Iterator An iterator in C++ is a concept that refines the iterator design pattern into a specific set of behaviors that work well with the.
Linked lists. Data structures to store a collection of items Data structures to store a collection of items are commonly used Typical operations on such.
C String, Proper Type, and String Objects Andy Wang COP 4530: Data Structures, Algorithms, and Generic Programming.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
The List ADT Reading: Sections 3.2, 3.3, 3.5.
Binary Trees Data Structures & OO Development I 1 Computer Science Dept Va Tech June 2006 ©2006 McQuain & Ribbens Binary Trees A binary tree is either.
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.
1 Circular, Doubly-Linked Lists Node Composition List Class Pushing and Popping Values Insert and Erase at Arbitrary Locations List Implementation.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
1 Generic Positional Containers and Double-Ended Queues.
Cpt S 122 – Data Structures Abstract Data Types
Chapter 4 The easy stuff.
Copy Constructor / Destructors Stacks and Queues
The List ADT Sections 3.2, 3.3, 3.5 Introduction
A Doubly Linked List There’s the need to access a list in reverse order prev next data dnode header 1.
Andy Wang Data Structures, Algorithms, and Generic Programming
The Bag and Sequence Classes with Linked Lists
Introduction to Linked Lists
Pointers and Linked Lists
Chapter 16-2 Linked Structures
Linked Lists.
Object Oriented Programming COP3330 / CGS5409
Generic Positional Containers and Double-Ended Queues
Linked List (Part I) Data structure.
Lists List: finite sequence of data elements
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
[Chapter 4; Chapter 6, pp ] CSC 143 Linked Lists [Chapter 4; Chapter 6, pp ]
Abstraction: Generic Programming, pt. 2
Doubly Linked List Implementation
Lists - I The List ADT.
Lists - I The List ADT.
Copyright © – Curt Hill STL List Details Copyright © – Curt Hill.
Doubly Linked List Implementation
Chapter 3 Lists, Stacks, and Queues
The List Container and Iterators
Presentation transcript:

A Generic List Class and Linked Lists Andy Wang Data Structures, Algorithms, and Generic Programming

Lists in Everyday Life Shopping list To-do list Dave Letterman’s top 10 list My cat’s revenge list Shopping vector? What if you want to insert an item? What if you want to insert an item?

List Wish List Insert an element Remove an element Remove all items Assignment operator Comparison operators Constructors/destructors Generic class Convenient way to iterate through the list

Iterator Motivating example char A[10] = { ‘a’, ‘b’, ‘c’, …’j’ }; char *j; for (j = A; j != A + 10; j++) { cout << *j << endl; }

Iterator A generalized model A way to initialize at the front and back of a list A way to initialize at the front and back of a list A way to move to the next or previous position A way to move to the next or previous position A way to detect the end of an iteration A way to detect the end of an iteration A way to retrieve the current value A way to retrieve the current value A way to compare two iterators at the same location A way to compare two iterators at the same location

List Iterator Wish List Return the first item Return the last item Return the current item Increment to the next item Decrement to previous item Detect the end of an iteration Compare iterators for equality Generic class

List Public Interface Read-only accessor functions unsigned int Size() const; int Empty() const;

List Public Interface (2) Locating places on the list Iterator Begin() const; Iterator End() const; Accessing values on the list T& Front() const; T& Back() const;

List Public Interface (3) Write functions int PushFront(const T& t); int PushBack(const T& t); int PopFront(); int PopBack(); int Insert(Iterator& I, const T& t); int Remove(Iterator& I); unsigned int Remove(const T& t); void Clear();

List Public Interface (4) Constructors and destructor TList();~TList(); TList & operator=(const TList & L); TList(const TList & L); Terminology support typedef T value_type; typedef TListIterator Iterator;

List Public Interface (5) Non-member functions int operator==(const TList & L1, const TList & L2); int operator!=(const TList & L1, const TList & L2); ostream operator & L);

List Complexity Requirements O(1) Runtime complexity Default Constructor Default Constructor PushFront(t), PushBack(t), Insert(I, t) PushFront(t), PushBack(t), Insert(I, t) PopFront(), PopBack(), Remove(I, t) PopFront(), PopBack(), Remove(I, t) Begin(), End() ; Begin(), End() ; Front(), Back() ; Front(), Back() ; Empty() ; Empty() ; Not available for vectors PushFront(t) for a vector Increment size Copy v[j] to v[j + 1] Assign v[0] = t  (size) (at least size)

List Complexity Requirements (2) O(Size()) Runtime complexity Copy constructor Copy constructor Assignment operator Assignment operator Destructor Destructor Size() Size() Clear() Clear() Remove(t) Remove(t) The maintenance cost of the size operation is  (size) (at least size) Incremental computation On-demand computation

List Iterator Public Interface Read-only operators int operator==(const iterator& I2) const; int operator!=(const iterator& I2) const; T& operator*() const; // return a reference to current value int Valid() const; // Iterator is pointing to a valid element Write operators iterator& operator=(const iterator& I); iterator& operator++(); // prefix iterator operator++(int); // postfix iterator& operator--(); // prefix iterator operator--(int); // postfix O(1) requirement for space and time

Using List TList KittyVengenceList; KittyVengenceList.PushFront(“toe biting”); “toe biting” “toe biting” KittyVengenceList.PushBack(“carpet littering”); “toe biting”, “carpet littering” “toe biting”, “carpet littering” KittyVengenceList.PushFront(“midnight howling”); “midnight howling”, “toe biting”, “carpet littering” “midnight howling”, “toe biting”, “carpet littering” KittyVengenceList.PushBack(“toilet drinking”); “midnight howling”, “toe biting”, “carpet littering”, “toilet drinking” “midnight howling”, “toe biting”, “carpet littering”, “toilet drinking” TList ::Iterator I; for (I = KittyVengenceList.Begin(); I != KittyVengenceList.End(); ++I) { // print list with << }

List Insertion Insert “furniture scratching” after “toe biting” // sequential search for (I = KittyVengenceList.Begin(); I.Valid(); ++I) { if (“toe biting” == *I) { break;}} KittyVengenceList.Insert(I, “furniture scratching”); “midnight howling”, “toe biting”, “furniture scratching”, “carpet littering”, “toilet drinking” “midnight howling”, “toe biting”, “furniture scratching”, “carpet littering”, “toilet drinking” // what happens if “toe biting” is not on the list?

Remove all copies of t from List TList ::Iterator I; for (I = KittyVengenceList.Begin(); I.Valid();) { if (t == *I) { KittyVengenceList.Remove(I); } else { ++I;}}

List and List Iterator Conceptual relationship Iterator L1 begincurrentend List: A, B, C, D, E, F begincurrentend Iterator L2

List Implementation Plan ListElement Pointers to the previous and next element Pointers to the previous and next element Value Value Defined within the List class, with limited scope class ListElement { // data ListElement *prev; ListElement *next; T value; // constructor ListElement(const T& t) : value(t); ListElement(const T& t) : value(t);}; value prev next value prev next value prev next No need for contiguous memory allocation

List Implementation Plan (2) Protected data Pointers to the first and the last element of the list Pointers to the first and the last element of the list Number of list elements Number of list elements template template class List { protected: ListElement* first; ListElement* last; unsigned int size; public:…};

Three Perspectives of List Client view List interface List interface ListIterator interface ListIterator interface Implementation view Sequentially ordered list elements Sequentially ordered list elements System view List elements connected by pointers List elements connected by pointers

List Iterator Implementation Plan Protected data Pointer to the current list element Pointer to the current list element template template class ListIterator { protected: ListElement* curr; public: ListIterator& operator++(); …};

Iterator operator++() Set curr to the next list element template template ListIterator<T>& ListIterator ::operator++() { curr = (*curr).next; // curr->next return *this; } value prev next value prev next value prev next curr ListIterator ListElement (*curr).next

Common Implementation Pitfalls Forget to update first, last, and size Forget to handle special cases Empty list Empty list List with one element List with one element List with more than one elements List with more than one elements

Debugging Tips Best debugging tools YOUR BRAIN YOUR BRAIN Careful analysis and design Careful analysis and design Writing code for readability and self- documentation Writing code for readability and self- documentation Best times to debug DESIGN TIME DESIGN TIME Coding time Coding time

Defining class TList Defining class TList template template class TList { friend class TListIterator ; public: typedef t value_type; typedef TListIterator Iterator; // constructors and destructor TList();~TList(); TList(const TList & L); TList & operator=(const TList & L); // Read-only accessor functions unsigned int Size() const; int Empty() const; T& Front() const; T& Back() const; Iterator Begin() const; Iterator End() const; void Display(ostream os, char ofc = ‘\0’) const;

Defining class TList (2) // Write routines int PushFront(const T& t); int PushBack(const T& t); int PopFront(); int PopBack(); int Insert(Iterator& I, const T& t); int Remove(Iterator& I); unsigned int Remove(const T& t); void Clear();

Defining class TList (3) protected: class TListElement { friend class TList ; friend class TListIterator ; // data T value; TListElement *prev; TListElement *next; TListElement(const T& Tval); } ListElement *first; ListElement *last; unsigned int size; void Clone(const TList & L); };

Defining class TList (4) // global scope operators and functions template template int operator==(const TList & L1, const TList & L2); template template int operator!=(const TList & L1, const TList & L2); tempalte tempalte ostream& operator & L);

Defining class TListIterator Defining class TListIterator Template Template Class TListIterator { friend class TList ; public: typedef T value_type; // constructors TListIterator(); TListIterator(const TList & L); tListIterator(const TListIterator& I); void Initialize(const TList & L); void rInitialize(const TList & L); // read-only routines T& Retrieve() const; // return reference to curr int Valid() const;

Defining class TListIterator (2) // read-only operators int operator==(const TListIterator& I2) const; int operator!=(const TListIterator& I2) const; T& operator*() const; // same as retrieve // write operators TListIterator & operator=(const TListIterator & I); TListIterator & operator++(); // prefix TListIterator operator++(int); // postfix TListIterator & operator--(); // prefix TListIterator operator--(int); // postfix protected: TList ::TListElement *curr; };

Implementing class TList Implementing class TList Helper functions template template void TList ::Clear() { // deletes all list elements in the TList // and set data members to 0 } template template void TList ::Clone(const TList & L) { // makes *this a clone of L // first copy the static data and initialize the pointers // then the dynamic data in the non-empty case }

Implementing class TList (2) Constructors template template TList ::TListElement::TListElement(const T& t) : value(t), prev(0), next(0) { } template template TList ::TList() : first(0), last(0), size(0) { } template template TList ::TList(const TList & L) { Clone(L);}

Implementing class TList (3) Destructor template template TList ::~TList() { Clear();}

Implementing class TList (4) Read-only functions template TListIterator TList ::Begin() const { Iterator I; I.curr = first; return I; } template void TList ::Display(ostream &os, char ofc) const { TList ::Iterator I; if (ofc == ‘\0’) { for (I = Begin(); I.Valid(); ++I) { os << *I; } } else { for (I = Begin(); I.Valid(); ++I) { os << *I << ofc; }}}

Implementing class TList (5) Read-only functions template template ostream& operator & L2) { L2.Display(os); return os; }

Implementing class TList (6) Read-only functions template template int operator==(const TList & L1, const TList & L2) { if (L1.Size() != L2.Size()) { return 0; } for (TList ::Iterator I1(L1), I2(L2); I1.Valid() && I2.Valid; I1++, I2++) { if (*I1 != *I2) { return 0; }} return 1; }

Implementing class TList (7) Write functions template template int operator=(const TList & L) { if (this != &L) { Clear();Clone(L);} return *this; }

Implementing class TList (8) Insert template template int TList ::Insert(TListIterator & I, const T& t) { // call the Push methods when they apply // Insert at back if iterator is not valid // insert at front if iterator is at front // iterator is valid and not at front // 1. create a new element // 2. link new element into the list // 3. adjust size (if present) // 4. leave I at new entry and return } template template TListIterator TList ::Insert(const T& t) { TListIterator I = End(); Insert(I, t); return I; }

Implementing class TList (9) Remove template int TList ::Remove(TListIterator & I) { // call the Pop methods when they apply // make sure of consistent interaction with ends of list // first deal with the invalid iterator case // for a valid iterator and non-void list // deal with cases where I.curr == first or last // at this point, we are removing a link that’s neither first nor last // 1. remember list element to be removed, and advance iterator // 2. unlink old list element from the list // 3. delete old list element, adjust size and return } template int TList ::Remove(const T& t) { // use iterator I and call Remove(I) // be sure to take into account the similarity of Remove(I) and ++I }

Implementing class TListIterator Implementing class TListIterator Helper function template template TListIterator ::Initialize(const TList & L) { curr = L.first; } template template TListIterator ::rInitialize(const TList & L) { curr = L.last; }

Implementing class TListIterator (2) Constructors template template TListIterator ::TListIterator() : curr(0) { } template template TListIterator ::TListIterator(const TList & L) { Initialize(L);} template template TListIterator ::TListIterator(const TListIterator & I) : curr(I.curr) { }

Implementing class TListIterator (3) Read-only functions template template int TListIterator ::Valid() const { return curr != 0; } template template T& TListIterator ::Retrieve() const { if (curr == 0) { std:cerr << “TListIterator: invalid dereference” << endl; exit(EXIT_FAILURE);} return curr->value; }

Implementing class TListIterator (4) Operator functions template template T& TListIterator ::operator*() const { return curr->value; } template template int TListIterator ::operator==(const TListIterator & I2) const { if (curr == I2.curr) { return 1; } return 0; }