Linked List Containers. Concatenate Example Concatenate(LinkedList listB): Add all of the elements of a second list to the end of the first list Concatenate(LinkedList.

Slides:



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

Linked Lists Geletaw S..
Stacks, Queues, and Linked Lists
CSCE 3110 Data Structures & Algorithm Analysis
DATA STRUCTURES USING C++ Chapter 5
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.
Data Structures Using C++
CS Data Structures Chapter 4 Lists. Chain (1/3) Chain: Chain: A singly linked list in which the last node has a null link A singly linked list in.
Linked Lists CENG 213 Data Structures.
David Weinberg presents Linked Lists: The Background  Linked Lists are similar to ArrayLists in their appearance and method of manipulation  They do.
Queue Definition Ordered list with property: –All insertions take place at one end (tail) –All deletions take place at other end (head) Queue: Q = (a 0,
Queues. Queue Definition Ordered list with property: All insertions take place at one end (tail) All insertions take place at one end (tail) All deletions.
Chapter 17 Linked List Saurav Karmakar Spring 2007.
Review Learn about linked lists
1 Linked Lists Gordon College Prof. Brinton. 2 Linked List Basics Why use? 1.Efficient insertion or deletion into middle of list. (Arrays are not efficient.
Linked Lists Compiled by Dr. Mohammad Alhawarat CHAPTER 04.
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
Chapter 4.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 17: Linked Lists.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 17: Linked Lists.
Chapter 3: Arrays, Linked Lists, and Recursion
Chapter 4 1. Why “linked lists” 2 IndexWord A[0]BAT A[1]CAT A[2]EAT … A[n]WAT Insert “FAT” ? Or delete something.
Data Structures Using C++ 2E
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 15: Linked data structures.
Linked Lists list elements are stored, in memory, in an arbitrary order explicit information (called a link) is used to go from one element to the next.
C++ Classes and Data Structures Jeffrey S. Childs
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.
Linked List Containers. Linked List Example Polynomials –Interested in representing and manipulating polynomials –Polynomial defined as: Y = coef_n *
Linked List (Part II). Introduction  Definition of equivalence relation: A relation ≡ over a set S, is said to be an equivalence relation over S iff.
Data Structures Using Java1 Chapter 4 Linked Lists.
Department of Computer Science Data Structures Using C++ 2E Chapter 5 Linked Lists.
Slide 1 Linked Data Structures. Slide 2 Learning Objectives  Nodes and Linked Lists  Creating, searching  Linked List Applications  Stacks, queues.
Week 4 - Monday.  What did we talk about last time?  Queues  Implementing queues with circular arrays.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
APS105 Lists. Structures Arrays allow a collection of elements –All of the same type How to collect elements of different types? –Structures; in C: struct.
Winter 2006CISC121 - Prof. McLeod1 Stuff Deadline for assn 3 extended to Monday, the 13 th. Please note that the testing class for assn 3 has changed.
Linked List (Part I). Introduction  Weakness of storing an ordered list in array: Insertion and deletion of arbitrary elements are expensive. ○ Example:
Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists.
Data Structures Using C++1 Chapter 5 Linked Lists.
CS 367 Introduction to Data Structures Lecture 5.
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More Linking.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 17: Linked Lists. Objectives In this chapter, you will: – Learn about linked lists – Learn the basic properties of linked lists – Explore insertion.
Linked List Containers. Useful Linked List Add-Ons Are there new variables/changes to the lists as they have been defined that could make our jobs as.
1 Linked List. Outline Introduction Insertion Description Deletion Description Basic Node Implementation Conclusion.
1 Chapter 4 Unordered List. 2 Learning Objectives ● Describe the properties of an unordered list. ● Study sequential search and analyze its worst- case.
1 CS 132 Spring 2008 Chapter 5 Linked Lists p
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 17: Linked Lists.
Linked Lists and Generics Written by J.J. Shepherd.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 18: Linked Lists.
Lists List Implementations. 2 Linked List Review Recall from CMSC 201 –“A linked list is a linear collection of self- referential structures, called nodes,
 2015, Marcus Biel, Linked List Data Structure Marcus Biel, Software Craftsman
Arrays, Link Lists, and Recursion Chapter 3. Sorting Arrays: Insertion Sort Insertion Sort: Insertion sort is an elementary sorting algorithm that sorts.
LINKED LISTS.
Chapter 16: Linked Lists.
Lecture 6 of Computer Science II
C++ Programming:. Program Design Including
Pointers and Linked Lists
More Linking Up with Linked Lists
Prof. Neary Adapted from slides by Dr. Katherine Gibson
Linked List (Part I) Data structure.
Dynamic Data Structures and Generics
Intro to OOP with Java, C. Thomas Wu By : Zanariah Idrus
Data Structures Chapter 4: Linked Lists.
Presentation transcript:

Linked List Containers

Concatenate Example Concatenate(LinkedList listB): Add all of the elements of a second list to the end of the first list Concatenate(LinkedList listB): Add all of the elements of a second list to the end of the first list Three cases: Three cases: ListA is empty – Set head for listA to head of listB ListA is empty – Set head for listA to head of listB ListB is empty – No change, nothing to do ListB is empty – No change, nothing to do Both have data – Set pointer on last node of listA to head for listB Both have data – Set pointer on last node of listA to head for listB This version of concatenate is: This version of concatenate is: Easy to implement Easy to implement Destructive towards listsA and listB – as it potentially changes how listA and listB work from here on out (listA delete will now cause listB nodes to go away as well) Destructive towards listsA and listB – as it potentially changes how listA and listB work from here on out (listA delete will now cause listB nodes to go away as well)

Concatenate Example void LinkedList ::concatenate(const LinkedList & listB) { // empty list A if (!first) { first = listB.first; return; } if (!first) { first = listB.first; return; } else if (listB.first) // if b is empty do nothing { // get to end of my list (listA) // get to end of my list (listA) ListNode * current = first; ListNode * current = first; while (current->link != 0) { current = current->link; } while (current->link != 0) { current = current->link; } current->link = listB.first; current->link = listB.first;}}

Safer Concatenate Example LinkedList& LinkedList ::concatenate(const LinkedList & listB) { // make a copy of list A using copy constructor LinkedList returnList = *(new LinkedList(*this)); if (listB.first) // if b is empty do nothing, else add to end { ListNode * current =listB.first; ListNode * current =listB.first; while (current->link != 0) while (current->link != 0) {listA.add(current->value); current = current->link; } return returnList; } } This version returns a new LinkedList which is a copy of listA with copies of listB nodes added to the end. Changes to the new list don’t affect listA or listB.

Useful Linked List Add-Ons Are there new variables/changes to the lists as they have been defined that could make our jobs as programmers easier? Are there new variables/changes to the lists as they have been defined that could make our jobs as programmers easier? Size member variable Size member variable Be able to determine current size of list, bound positions for add, delete, etc. Be able to determine current size of list, bound positions for add, delete, etc. Maintaining a variable is cheap, counting the nodes every time size is called (the alternative) is not! Maintaining a variable is cheap, counting the nodes every time size is called (the alternative) is not! Tail pointer Tail pointer Significantly simplifies addition at end of list Significantly simplifies addition at end of list

Tail Pointers If doing a lot of adds to the end (which is natural), a tail pointer provides instant access to the last node If doing a lot of adds to the end (which is natural), a tail pointer provides instant access to the last node Does require some extra overhead in the add/delete functions to keep tail updated Does require some extra overhead in the add/delete functions to keep tail updated List Construction: first=tail=0; 1-node: first != 0 and first == tail List Construction: first=tail=0; 1-node: first != 0 and first == tail List1 Data1List1 Data2List1 Data3 tailfirst

Circular Lists Another improvement on LinkedLists: Another improvement on LinkedLists: Use link pointer of last node to point to the first node. Use link pointer of last node to point to the first node. Changes to implementation: Changes to implementation: Check to see if at last node: Check to see if at last node: test “if (current -> link == first)” instead of “if (current->link == 0)” Insertion and deletion need to preserve property that last nodes link is always set equal to first Insertion and deletion need to preserve property that last nodes link is always set equal to first

Circular List Implementation Retrofitting our LinkedList to make circular: Don’t want to have just a head pointer: Why? Don’t want to have just a head pointer: Why? If inserting at tail, have to traverse the whole list from head to get to tail to update the tails link If inserting at tail, have to traverse the whole list from head to get to tail to update the tails link If inserting at head, need to find last node to point its link to new head - this also traverses the whole list If inserting at head, need to find last node to point its link to new head - this also traverses the whole list Circular linked lists are much more efficient if use tail (last) pointer as the pointer for the list. Circular linked lists are much more efficient if use tail (last) pointer as the pointer for the list. Two pointers (head and tail) are actually overkill.. why? Two pointers (head and tail) are actually overkill.. why?

Circular Linked Lists List1 Data1List1 Data2List1 Data3 tailfirst Can access head via tail->link in one step so don’t need head pointer

Circular Linked List void insertAtFront(ListNode *x) { if (tail == 0) { // empty list, tail = x; x-> link = x; // point to yourself }else{ x->link = tail->link; // point new head link to old head tail->link = x; // point tail to new head }} insertAtRear() only requires adding tail = x in the else statement (to update rear to new node)

Linked List Examples Now that the basic structures of LinkedLists have been defined, what are some potential applications? Now that the basic structures of LinkedLists have been defined, what are some potential applications? Target problems where can take advantage of LinkedList memory usage model Target problems where can take advantage of LinkedList memory usage model Target problems where can take advantage of dynamic aspects of LinkedList Target problems where can take advantage of dynamic aspects of LinkedList

Linked List Example Polynomials Polynomials Interested in representing and manipulating polynomials Interested in representing and manipulating polynomials Polynomial defined as: Polynomial defined as: Y = coef_n * x exp_n + coef_n-1 * x exp_n-1 + … coef_0 * x 0 Y = coef_n * x exp_n + coef_n-1 * x exp_n-1 + … coef_0 * x 0 Examples: Examples: 3x x x 14 – 3x x 6

Polynomials Has a very nice linked representation Has a very nice linked representation In particular, able to take advantage of sparse number of coefficients with a linked representation In particular, able to take advantage of sparse number of coefficients with a linked representation Compare against an array that holds the coefficients and exponents for all possible indices from 0 to max degree Compare against an array that holds the coefficients and exponents for all possible indices from 0 to max degree Horribly wasteful in terms of space Horribly wasteful in terms of space What if we had an array of Term objects, where a Term was an exponent/coefficient What if we had an array of Term objects, where a Term was an exponent/coefficient Only need enough array space to hold true terms, so amount of space required ok.. However, we’ll see this is still inflexible. Only need enough array space to hold true terms, so amount of space required ok.. However, we’ll see this is still inflexible.

Polynomials For each component of the polynomial, need to store coefficient and exponent For each component of the polynomial, need to store coefficient and exponent struct Term { int coef; int exp; void Init(int c, int e) { coef = c; exp = e;} };

Polynomials Polynomial itself implemented by a templated LinkedList of Terms Polynomial itself implemented by a templated LinkedList of Terms class Polynomial {private: LinkedList poly; };

Polynomials Adding Polynomials: Adding Polynomials: 3x 3 + 2x x 3 + 3x x 3 + 3x 2 + 5================= 5x 3 + 3x 2 + 2x + 6 5x 3 + 3x 2 + 2x + 6

Polynomials Adding Polynomials: Adding Polynomials: Iterate through both lists Iterate through both lists If exponent1 == exponent2, If exponent1 == exponent2, CoefficientSum = Coefficient1 + Coefficient2 CoefficientSum = Coefficient1 + Coefficient2 If CoefficentSum != 0, add term to new polynomial representing answer If CoefficentSum != 0, add term to new polynomial representing answer Else, Else, Find higher exponent Find higher exponent Add term to new polynomial representing answer Add term to new polynomial representing answer

Polynomials

Polynomials The “Answer” polynomial is where LinkedLists have another win. There is now way beforehand to know how may terms there will be in the answer polynomial The “Answer” polynomial is where LinkedLists have another win. There is now way beforehand to know how may terms there will be in the answer polynomial Number of terms is anywhere from (the size of the largest list) to the size of the largest list plus the size of the smallest list) Number of terms is anywhere from (the size of the largest list) to the size of the largest list plus the size of the smallest list) With an array representation, would have to overallocate to handle large answers With an array representation, would have to overallocate to handle large answers With LinkedLists, just grab a new Node when need it. With LinkedLists, just grab a new Node when need it.

Polynomials Overload + operator to perform polynomial addition Overload + operator to perform polynomial addition Implementation in page 193 Implementation in page 193

Example: Equivalence Classes Another Example of Linked List Usage: Another Example of Linked List Usage: Finding Equivalence Classes Definition: Definition: Given a relation (, ==, …), the relation is an equivalence relation over a set S if the relation is reflexive, symmetric, and transitive over S

Equivalence Relations Reflexive Reflexive A ? A Is < Reflexive? A < A No Is = Reflexive?A == AYes Symmetric: Symmetric: If A ? B, then B ? A If A ? B, then B ? A Is < Symmetric? A < B, then B < A No Is = Symmetric? A = B, then B = A Yes

Equivalence Relations Transitive Transitive If A ? B and B ? C, then A ? C If A ? B and B ? C, then A ? C Is < transitive?A < B, B < C, A < C Yes Is < transitive?A < B, B < C, A < C Yes Is = transitive?A = B, B = C, A = C Yes Is = transitive?A = B, B = C, A = C Yes = is reflexive, symmetric, and transitive, so it is an equivalence relation < fails on reflexive and symmetric, so it is not an equivalence relation

Equivalence Classes Effect of equivalence relations is the ability to partition a set S into classes such that any two members of S, x and y, are in the same class if x equiv y. Effect of equivalence relations is the ability to partition a set S into classes such that any two members of S, x and y, are in the same class if x equiv y. Classes are called equivalence classes Classes are called equivalence classes

Equivalence Classes Equivalence Class Example: Let our relationship be = mod 3 Reflexive 5 mod 3 = 5 mod 3 => 2 = 2 Yes Symmetric 5 mod 3 = 8 mod 3, then 8 mod 3 = 5 mod 3 2 = 2, then 2 = 2 Yes Transitive 5 mod 3 = 8 mod 3, 8 mod 3 = 14 mod 3, then 5 mod 3 = 14 mod 3 2 = 2, 2 = 2, then 2 = 2, Yes

Equivalence Classes Equivalence Classes: Equivalence Classes: All numbers that are = mod 3 are in the same equivalence class All numbers that are = mod 3 are in the same equivalence class Mod 3 = 0Mod 3 = 1Mod 3 = 2 {0,3,6,9,…}{1,4,7,10,…} {2,5,8,11,…}

Equivalence Classes Goal: Goal: Given a list of equivalence relations between items x and y, construct the equivalence classes Given a list of equivalence relations between items x and y, construct the equivalence classes Relations: 0 = 4, 3 = 1, 6 = 10, 8 = 9, 7 = 4, 6 = 8, 3 = 5, 2= 11, 11 = 0 Relations: 0 = 4, 3 = 1, 6 = 10, 8 = 9, 7 = 4, 6 = 8, 3 = 5, 2= 11, 11 = 0 Classes: {0,2,4,7,11}, {1,3,5,}, {6,8,9,10} Classes: {0,2,4,7,11}, {1,3,5,}, {6,8,9,10}

Equivalence Classes Could build N by N (N = number of total items) matrix indicating relationship, but most of entries are likely to be zero Could build N by N (N = number of total items) matrix indicating relationship, but most of entries are likely to be zero Instead, use an array of pointers for 1-dimensional list of all items, where for each item, the pointer points to a list of all items that are equivalent in the input Instead, use an array of pointers for 1-dimensional list of all items, where for each item, the pointer points to a list of all items that are equivalent in the input For each item I = J input, For each item I = J input, Add J to I’s list Add I to J’s list

Equivalence Classes

Equivalence Classes To find equivalence classes, To find equivalence classes, Start at front of array Start at front of array Print X, Mark as printed Print X, Mark as printed Print all things equivalent to X (follow its list), mark as printed Print all things equivalent to X (follow its list), mark as printed For each thing equivalent to X, print the appropriate list For each thing equivalent to X, print the appropriate list

Equivalence Classes Include an array to indicate whether that data has already been written: Include an array to indicate whether that data has already been written: boolean out[n] initially all set to false Code on pages 205, 206 of book Code on pages 205, 206 of book

Equivalence Classes First Steps of Test Run on Previous Data First Steps of Test Run on Previous Data OutputStack Out Array FFFFFFFFFFFF NC: 0 TFFFFFFFFFFF NC: 0,11 Top->11TFFFFFFFFFFT NC: 0,11,4 Top->4,11TFFFTFFFFFFT NC: 0,11,4,7 Top->7,11TFFFTFFTFFFT

Complexity of Equivalence Class Operations Initialization Initialization Initializing sequence and output arrays with n possible values: O(n) Processing each pair of input – 2 steps * m inputs: O(m) So, pre-processing requires: O(n+m) Traversing list: Traversing list: n possible lists to look at, 2m entries total on the lists Only process list if haven’t already written So only looks at each entry in the array once (upper bound of n) Since only looks at each array once, only looks at nodes underneath the array entry once (upper bound of 2m) So traverse time is O(n+m)

Doubly Linked Lists Biggest problem with linked lists as we’ve used so far: Biggest problem with linked lists as we’ve used so far: Can only navigate in one direction Can only navigate in one direction Requires traversals from front to a position, even if currently located right behind where want to be Requires traversals from front to a position, even if currently located right behind where want to be Requires “trailing pointer” if want to easily get access to previous node for current node Requires “trailing pointer” if want to easily get access to previous node for current node When update current to current->next, update prev to current When update current to current->next, update prev to current

Doubly Linked Lists Work around these issues by storing both the left and right side neighbors of a linked list Work around these issues by storing both the left and right side neighbors of a linked list Makes add, delete, and other array manipulation operators more complicated as have to preserve doubly linked property Makes add, delete, and other array manipulation operators more complicated as have to preserve doubly linked property

Doubly Linked Lists Definition: Definition: class DblList; // forward declaration class DblListNode { friend class DblList; private: int data; DblListNode *right, *left; };

Doubly Linked Lists class DblList {public: // list manipulation private: DblListNode* first; DblListNode* first;};

Doubly Linked Lists LEFTDATARIGHTLEFT10RIGHTLEFT15RIGHTLEFT29RIGHT Example Node 3 Node Circular Doubly Linked List

Note that, given a pointer p, Note that, given a pointer p, p = p->left->right = p->right->left Going back and forth is equally easy. Going back and forth is equally easy.

Doubly Linked List void DblList::Insert(DblListNode *new, DblListNode *current) { // insert new after x new->left = current; new->right = current->right; current->right->left = new; current->right = new; } 10L current R12L R R11L new

Doubly Linked List void DblList::Delete(DblListNode *toDelete) { // delete node pointed to by toDelete toDelete->left->right = toDelete->right; toDelete->right->left = toDelete->left; delete toDelete; } 10LR12LR11L toDelete