Upload
phoebe-rice
View
228
Download
1
Embed Size (px)
Citation preview
Linked List Linked List ContainersContainers
Concatenate ExampleConcatenate Example Concatenate(LinkedList<Type> listB): Add all Concatenate(LinkedList<Type> listB): Add all
of the elements of a second list to the end of of the elements of a second list to the end of the first list the first list
Three cases: Three cases: ListA is empty – Set head for listA to head of listBListA is empty – Set head for listA to head of listB ListB is empty – No change, nothing to doListB is empty – No change, nothing to do Both have data – Set pointer on last node of listA Both have data – Set pointer on last node of listA
to head for listBto head for listB This version of concatenate is:This version of concatenate is:
Easy to implementEasy to implement Destructive towards listsA and listB – as it Destructive towards listsA and listB – as it
potentially changes how listA and listB work from potentially changes how listA and listB work from here on out (listA delete will now cause listB nodes here on out (listA delete will now cause listB nodes to go away as well)to go away as well)
Concatenate ExampleConcatenate Examplevoid LinkedList<Type>::concatenate(const void LinkedList<Type>::concatenate(const
LinkedList<Type> & listB) LinkedList<Type> & listB) {{// empty list A// empty list A
if (!first) { first = listB.first; return; } if (!first) { first = listB.first; return; }
else if (listB.first) // if b is empty do nothingelse if (listB.first) // if b is empty do nothing{{
// get to end of my list (listA)// get to end of my list (listA) ListNode<Type>* current = first;ListNode<Type>* 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 Safer Concatenate ExampleExampleLinkedList& LinkedList<Type>::concatenate(const LinkedList<Type> & listB) LinkedList& LinkedList<Type>::concatenate(const LinkedList<Type> & listB)
{{// make a copy of list A using copy constructor// make a copy of list A using copy constructorLinkedList returnList = *(new LinkedList(*this));LinkedList returnList = *(new LinkedList(*this));
if (listB.first) // if b is empty do nothing, else add to endif (listB.first) // if b is empty do nothing, else add to end{{
ListNode<Type>* current =listB.first;ListNode<Type>* current =listB.first; while (current->link != 0)while (current->link != 0)
{ { listA.add(current->value); listA.add(current->value); current = current->link; current = current->link; }}
return returnList; }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-Useful Linked List Add-OnsOns
Are there new variables/changes to the Are there new variables/changes to the lists as they have been defined that could lists as they have been defined that could make our jobs as programmers easier?make our jobs as programmers easier?
Size member variableSize member variable Be able to determine current size of list, bound Be able to determine current size of list, bound
positions for add, delete, etc.positions for add, delete, etc. Maintaining a variable is cheap, counting the Maintaining a variable is cheap, counting the
nodes every time size is called (the alternative) nodes every time size is called (the alternative) is not!is not!
Tail pointerTail pointer Significantly simplifies addition at end of list Significantly simplifies addition at end of list
Tail PointersTail Pointers If doing a lot of adds to the end If doing a lot of adds to the end
(which is natural), a tail pointer (which is natural), a tail pointer provides instant access to the last provides instant access to the last nodenode
Does require some extra overhead in Does require some extra overhead in the add/delete functions to keep tail the add/delete functions to keep tail updatedupdated
List Construction: first=tail=0; 1-List Construction: first=tail=0; 1-node: first != 0 and first == tailnode: first != 0 and first == tail
List1 Data1 List1 Data2 List1 Data3
tailfirst
Circular ListsCircular Lists Another improvement on LinkedLists:Another improvement on LinkedLists:
Use link pointer of last node to point to the Use link pointer of last node to point to the first node.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)”test “if (current -> link == first)”instead of “if (current->link == 0)”instead of “if (current->link == 0)”
Insertion and deletion need to preserve Insertion and deletion need to preserve property that last nodes link is always set property that last nodes link is always set equal to firstequal to first
Circular List Circular List ImplementationImplementation
Retrofitting our LinkedList to make circular: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 If inserting at tail, have to traverse the whole list from head to get to tail to update the tails link from head to get to tail to update the tails link
If inserting at head, need to find last node to point If inserting at head, need to find last node to point its link to new head - this also traverses the whole its link to new head - this also traverses the whole listlist
Circular linked lists are much more efficient if Circular linked lists are much more efficient if use tail (last) pointer as the pointer for the list.use tail (last) pointer as the pointer for the list.
Two pointers (head and tail) are actually Two pointers (head and tail) are actually overkill .. why?overkill .. why?
Circular Linked ListsCircular Linked Lists
List1 Data1 List1 Data2 List1 Data3
tailfirst
Can access head via tail->linkin one step so don’t need head pointer
Circular Linked ListCircular Linked Listvoid insertAtFront(ListNode <Type> *x)void insertAtFront(ListNode <Type> *x){{
if (tail == 0) { // empty list, if (tail == 0) { // empty list, tail = x; x-> link = x; // point to yourselftail = x; x-> link = x; // point to yourself
}}elseelse{{
x->link = tail->link; // point new head link to old headx->link = tail->link; // point new head link to old headtail->link = x; // point tail to new headtail->link = x; // point tail to new head
}}}}
insertAtRear() only requires adding tail = x in the else statement insertAtRear() only requires adding tail = x in the else statement (to update rear to new node) (to update rear to new node)
Linked List ExamplesLinked List Examples
Now that the basic structures of Now that the basic structures of LinkedLists have been defined, what LinkedLists have been defined, what are some potential applications?are some potential applications?
Target problems where can take Target problems where can take advantage of LinkedList memory usage advantage of LinkedList memory usage modelmodel
Target problems where can take Target problems where can take advantage of dynamic aspects of advantage of dynamic aspects of LinkedListLinkedList
Linked List ExampleLinked List Example
PolynomialsPolynomials Interested in representing and Interested in representing and
manipulating polynomials manipulating polynomials Polynomial defined as:Polynomial defined as:
Y = coef_n * xY = coef_n * xexp_n exp_n ++ coef_n-1 * xcoef_n-1 * xexp_n-1 exp_n-1 + … + … coef_0 * xcoef_0 * x00
Examples:Examples:3x3x1414 + 2x + 2x88 + 1 + 18x8x1414 – 3x – 3x1010 + 10x + 10x66
PolynomialsPolynomials
Has a very nice linked representationHas a very nice linked representation In particular, able to take advantage of In particular, able to take advantage of sparsesparse
number of coefficients with a linked representationnumber of coefficients with a linked representation
Compare against an array that holds the Compare against an array that holds the coefficients and exponents for all possible indices coefficients and exponents for all possible indices from 0 to max degreefrom 0 to max degree
Horribly wasteful in terms of spaceHorribly wasteful in terms of space
What if we had an array of Term objects, where a What if we had an array of Term objects, where a Term was an exponent/coefficientTerm was an exponent/coefficient
Only need enough array space to hold true terms, so Only need enough array space to hold true terms, so amount of space required ok.. However, we’ll see this is amount of space required ok.. However, we’ll see this is still inflexible.still inflexible.
PolynomialsPolynomials For each component of the polynomial, For each component of the polynomial,
need to store need to store coefficientcoefficient and and exponentexponent
struct Term struct Term { {
int coef;int coef;int exp;int exp;void Init(int c, int e) { coef = c; exp = e;}void Init(int c, int e) { coef = c; exp = e;}
};};
PolynomialsPolynomials
Polynomial itself implemented by a Polynomial itself implemented by a templated LinkedList of Termstemplated LinkedList of Terms
class Polynomialclass Polynomial
{{
private:private:
LinkedList<Term> poly;LinkedList<Term> poly;
};};
PolynomialsPolynomials
Adding Polynomials:Adding Polynomials:
3x3x33 + 2x + 1 + 2x + 1
++
2x2x33 + 3x + 3x22 + 5 + 5
==================================
5x5x33 + 3x + 3x22 + 2x + 6 + 2x + 6
PolynomialsPolynomials
Adding Polynomials:Adding Polynomials: Iterate through both listsIterate through both lists If exponent1 == exponent2,If exponent1 == exponent2,
CoefficientSum = Coefficient1 + Coefficient2CoefficientSum = Coefficient1 + Coefficient2 If CoefficentSum != 0, add term to new If CoefficentSum != 0, add term to new
polynomial representing answerpolynomial representing answer Else, Else,
Find higher exponentFind higher exponent Add term to new polynomial representing Add term to new polynomial representing
answeranswer
PolynomialsPolynomials
3 3 2 1 1 0
2 3 3 2 5 0
5 3 3 2 2 1 6 0
PolynomialsPolynomials
The “Answer” polynomial is where The “Answer” polynomial is where LinkedLists have another win. There is LinkedLists have another win. There is now way beforehand to know how may now way beforehand to know how may terms there will be in the answer terms there will be in the answer polynomial polynomial Number of terms is anywhere from (the Number of terms is anywhere from (the
size of the largest list) to the size of the size of the largest list) to the size of the largest list plus the size of the smallest list)largest list plus the size of the smallest list)
With an array representation, would have With an array representation, would have to overallocate to handle large answersto overallocate to handle large answers
With LinkedLists, just grab a new Node With LinkedLists, just grab a new Node when need it.when need it.
PolynomialsPolynomials
Overload + operator to perform Overload + operator to perform polynomial additionpolynomial addition
Implementation in page 193Implementation in page 193
Example: Equivalence Example: Equivalence ClassesClasses
Another Example of Linked List Usage: Another Example of Linked List Usage:
Finding Equivalence ClassesFinding Equivalence Classes
Definition:Definition:
Given a relation (<, >, ==, …),Given a relation (<, >, ==, …),
the relation is an equivalence relation the relation is an equivalence relation over a set S if the relation is reflexive, over a set S if the relation is reflexive, symmetric, and transitive over Ssymmetric, and transitive over S
Equivalence RelationsEquivalence Relations ReflexiveReflexive
A ? AA ? AIs < Reflexive? Is < Reflexive? A < A A < A NoNoIs = Reflexive?Is = Reflexive? A == AA == A YesYes
Symmetric:Symmetric: If A ? B, then B ? AIf A ? B, then B ? A
Is < Symmetric?Is < Symmetric? A < B, then B < A No A < B, then B < A NoIs = Symmetric?Is = Symmetric? A = B, then B = A Yes A = B, then B = A Yes
Equivalence RelationsEquivalence Relations TransitiveTransitive If A ? B and B ? C, then A ? CIf A ? B and B ? C, then A ? C Is < transitive?Is < transitive? A < B, B < C, A < C A < B, B < C, A < C
YesYes Is = transitive?Is = transitive? A = B, B = C, A = C A = B, B = C, A = C
YesYes
= is reflexive, symmetric, and transitive, so it = is reflexive, symmetric, and transitive, so it is an equivalence relationis an equivalence relation
< fails on reflexive and symmetric, so it is not < fails on reflexive and symmetric, so it is not an equivalence relationan equivalence relation
Equivalence ClassesEquivalence Classes
Effect of equivalence relations is the Effect of equivalence relations is the ability to partition a set S into ability to partition a set S into classes such that any two members classes such that any two members of S, x and y, are in the same class if of S, x and y, are in the same class if x equiv yx equiv y..
Classes are called equivalence Classes are called equivalence classesclasses
Equivalence ClassesEquivalence Classes
Equivalence Class Example:Equivalence Class Example:Let our relationship be = mod 3Let our relationship be = mod 3
ReflexiveReflexive5 mod 3 = 5 mod 3 => 2 = 2 Yes5 mod 3 = 5 mod 3 => 2 = 2 Yes
SymmetricSymmetric5 mod 3 = 8 mod 3, then 8 mod 3 = 5 mod 35 mod 3 = 8 mod 3, then 8 mod 3 = 5 mod 32 = 2, then 2 = 2 Yes2 = 2, then 2 = 2 Yes
TransitiveTransitive5 mod 3 = 8 mod 3, 8 mod 3 = 14 mod 3, then 5 5 mod 3 = 8 mod 3, 8 mod 3 = 14 mod 3, then 5 mod 3 = 14 mod 3mod 3 = 14 mod 32 = 2, 2 = 2, then 2 = 2, Yes2 = 2, 2 = 2, then 2 = 2, Yes
Equivalence ClassesEquivalence Classes
Equivalence Classes:Equivalence Classes: All numbers that are = mod 3 are in the All numbers that are = mod 3 are in the
same equivalence classsame equivalence class
Mod 3 = 0Mod 3 = 0 Mod 3 = 1Mod 3 = 1 Mod Mod 3 = 23 = 2
{0,3,6,9,…}{0,3,6,9,…} {1,4,7,10,…} {1,4,7,10,…} {2,5,8,11,…}{2,5,8,11,…}
Equivalence ClassesEquivalence Classes
Goal:Goal: Given a list of equivalence relations between Given a list of equivalence relations between
items x and y, construct the equivalence items x and y, construct the equivalence classesclasses
Relations: 0 = 4, 3 = 1, 6 = 10, 8 = 9, 7 = Relations: 0 = 4, 3 = 1, 6 = 10, 8 = 9, 7 = 4, 6 = 8, 3 = 5, 2= 11, 11 = 04, 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 ClassesEquivalence Classes
Could build N by N (N = number of total Could build N by N (N = number of total items) matrix indicating relationship, but items) matrix indicating relationship, but most of entries are likely to be zeromost of entries are likely to be zero
Instead, use an array of pointers for 1-Instead, use an array of pointers for 1-dimensional list of all items, where for dimensional list of all items, where for each item, the pointer points to a list of all each item, the pointer points to a list of all items that are equivalent in the inputitems that are equivalent in the input
For each item I = J input,For each item I = J input,
Add J to I’s listAdd J to I’s list
Add I to J’s listAdd I to J’s list
Equivalence ClassesEquivalence Classes
1 2 3 4 5 6 7 8 9 10 110
11
4
3 11 5 7
1 0
3 8 4 6 8 6 0
10 9 2
Equivalence ClassesEquivalence Classes
To find equivalence classes,To find equivalence classes, Start at front of arrayStart at front of array Print X, Mark as printedPrint X, Mark as printed Print all things equivalent to X (follow Print all things equivalent to X (follow
its list), mark as printedits list), mark as printed For each thing equivalent to X, print the For each thing equivalent to X, print the
appropriate listappropriate list
Equivalence ClassesEquivalence Classes
Include an array to indicate whether Include an array to indicate whether that data has already been written:that data has already been written:
boolean out[n] boolean out[n] initially all set to falseinitially all set to false
Code on pages 205, 206 of bookCode on pages 205, 206 of book
Equivalence ClassesEquivalence Classes
First Steps of Test Run on Previous Data First Steps of Test Run on Previous Data
OutputOutput StackStack Out ArrayOut Array
FFFFFFFFFFFFFFFFFFFFFFFF
NC: 0NC: 0 TFFFFFFFFFTFFFFFFFFFFFFF
NC: 0,11NC: 0,11 Top->11Top->11 TFFFFFFFFFTFFFFFFFFFFTFT
NC: 0,11,4NC: 0,11,4 Top->4,11Top->4,11 TFFFTFFFFFTFFFTFFFFFFTFT
NC: 0,11,4,7NC: 0,11,4,7 Top->7,11Top->7,11 TFFFTFFTFFTFFFTFFTFFFTFT
Complexity of Complexity of Equivalence Class Equivalence Class
OperationsOperations InitializationInitializationInitializing sequence and output arrays with n possible Initializing sequence and output arrays with n possible
values: O(n)values: O(n)Processing each pair of input – 2 steps * m inputs: O(m)Processing each pair of input – 2 steps * m inputs: O(m)So, pre-processing requires: O(n+m)So, pre-processing requires: O(n+m)
Traversing list:Traversing list:n possible lists to look at, 2m entries total on the lists n possible lists to look at, 2m entries total on the lists Only process list if haven’t already writtenOnly process list if haven’t already written
So only looks at each entry in the array once (upper So only looks at each entry in the array once (upper bound of n)bound of n)
Since only looks at each array once, only looks at nodes Since only looks at each array once, only looks at nodes underneath the array entry once (upper bound of 2m)underneath the array entry once (upper bound of 2m)
So traverse time is O(n+m)So traverse time is O(n+m)
Doubly Linked ListsDoubly Linked Lists
Biggest problem with linked lists as Biggest problem with linked lists as we’ve used so far: we’ve used so far: Can only navigate in one directionCan only navigate in one direction Requires traversals from front to a position, Requires traversals from front to a position,
even if currently located right behind where even if currently located right behind where want to bewant to be
Requires “trailing pointer” if want to easily Requires “trailing pointer” if want to easily get access to previous node for current nodeget access to previous node for current node
When update current to current->next, update When update current to current->next, update prev to currentprev to current
Doubly Linked ListsDoubly Linked Lists
Work around these issues by storing Work around these issues by storing both the left and right side both the left and right side neighbors of a linked listneighbors of a linked list
Makes add, delete, and other array Makes add, delete, and other array manipulation operators more manipulation operators more complicated as have to preserve complicated as have to preserve doubly linked propertydoubly linked property
Doubly Linked ListsDoubly Linked Lists
Definition:Definition:
class DblList; // forward declarationclass DblList; // forward declaration
class DblListNodeclass DblListNode
{{
friend class DblList;friend class DblList;
private:private:
int data;int data;
DblListNode *right, *left;DblListNode *right, *left;
};};
Doubly Linked ListsDoubly Linked Lists
class DblListclass DblList
{{
public:public:
// list manipulation// list manipulation
private:private:
DblListNode* first;DblListNode* first;
};};
Doubly Linked ListsDoubly Linked Lists
LEFT DATA RIGHT
LEFT 10 RIGHT
LEFT 15 RIGHT
LEFT 29 RIGHT
Example Node
3 Node CircularDoubly Linked List
Doubly Linked ListDoubly Linked List
Note that, given a pointer p, Note that, given a pointer p, p = p->left->right = p->right->leftp = p->left->right = p->right->left
Going back and forth is equally easy.Going back and forth is equally easy.
Doubly Linked ListDoubly Linked List
void DblList::Insert(DblListNode *new, void DblList::Insert(DblListNode *new, DblListNode *current)DblListNode *current)
{{// insert new after x// insert new after xnew->left = current; new->left = current; new->right = current->right;new->right = current->right;current->right->left = new;current->right->left = new;current->right = new;current->right = new;
}}
10L
current
R12LR
R11L
new
Doubly Linked ListDoubly Linked List
void DblList::Delete(DblListNode void DblList::Delete(DblListNode *toDelete)*toDelete)
{{// delete node pointed to by toDelete// delete node pointed to by toDeletetoDelete->left->right = toDelete-toDelete->left->right = toDelete->right;>right;toDelete->right->left = toDelete->left;toDelete->right->left = toDelete->left;delete toDelete;delete toDelete;
}} 10L R12LR11L
toDelete