Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple...
-
Upload
kerrie-obrien -
Category
Documents
-
view
223 -
download
0
Transcript of Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple...
Linked List Linked List ContainersContainers
Linked ListsLinked Lists
List consists of multiple listnodesList consists of multiple listnodes Each listnode consists of Each listnode consists of
DataData Pointer to another nodePointer to another node
Traditional view of data:Traditional view of data:
Data Data Data
Linked ListsLinked Lists
Insertion at a specific point:Insertion at a specific point:Get a new node (allocate from memory)Get a new node (allocate from memory)Set data pointerSet data pointerSet link of new node to previous node linkSet link of new node to previous node linkSet link of previous node link to new nodeSet link of previous node link to new node
FAT MAT RAT
HAT
Linked ListsLinked Lists
Deletion at a specific point:Deletion at a specific point:
Set the link of the previous node to Set the link of the previous node to the link of the node to delete.the link of the node to delete.
FAT MAT RAT
FAT RAT
Linked List Linked List RepresentationsRepresentations
Can locate data in any place in memory, Can locate data in any place in memory, not required to be sequentialnot required to be sequential
No requirements on computing size of No requirements on computing size of list beforehandlist beforehand
No more space than needNo more space than need No bounds on spaceNo bounds on space No resizingNo resizing Still fairly trivial to manage and Still fairly trivial to manage and
understandunderstand
Linked Lists in C++Linked Lists in C++
Need to define a ListNode Class that Need to define a ListNode Class that represents: represents: Data Data Pointer to another ListNodePointer to another ListNode
Need to define a LinkedList Class Need to define a LinkedList Class that provides container operations that provides container operations (Add, Delete, etc), using ListNodes (Add, Delete, etc), using ListNodes to implement the storage for the to implement the storage for the containercontainer
Linked Lists in C++Linked Lists in C++
Node definition:Node definition:
class nodeName class nodeName class ThreeLetterListNodeclass ThreeLetterListNode
{{ {{
private:private: private: private:
type dataName;type dataName; char data[3]; char data[3];
nodeName *link;nodeName *link; ThreeLetterListNode * ThreeLetterListNode * link;link;
}} }}
Linked Lists in C++Linked Lists in C++
Requirements for LinkedList construct:Requirements for LinkedList construct: Want to preserve encapsulation of nodes Want to preserve encapsulation of nodes
and ensure that updating the data and link and ensure that updating the data and link pointers are only accomplished by the pointers are only accomplished by the ListNode itself or the LinkedListListNode itself or the LinkedList
Arbitrary and unlimited amount of memoryArbitrary and unlimited amount of memory
Characterize the LinkedList as: A Characterize the LinkedList as: A LinkedList consists of zero or more LinkedList consists of zero or more objects of type ListNode.objects of type ListNode.
Linked ListsLinked Lists Linked List definition suggests that the List Linked List definition suggests that the List
object actually physically contains lots of object actually physically contains lots of ListNodes.ListNodes.
Contains a pointer, called Contains a pointer, called firstfirst, to one , to one ListNode, from which the rest of the ListNodes ListNode, from which the rest of the ListNodes can be found by following links.can be found by following links.
All ListNode objects are not physically All ListNode objects are not physically contained within the LinkedList objectcontained within the LinkedList object
To access private data members of ListNode To access private data members of ListNode class, without making the data members class, without making the data members public or having public functions to set data public or having public functions to set data and links, and links, make the LinkedList class a make the LinkedList class a friendfriend of the ListNode of the ListNode
class:class:
Linked ListsLinked Listsclass LinkedList; class LinkedList; // forward declaration// forward declaration
template <class Type>template <class Type>class ListNode {class ListNode {friend class LinkedList<Type>;friend class LinkedList<Type>;private:private: Type data;Type data; ListNode *link;ListNode *link;};};
template<class Type>template<class Type>class LinkedList {class LinkedList { public: // manipulation operationspublic: // manipulation operations private:private:
ListNode<Type> *first;ListNode<Type> *first;}}
LinkedList.h
ListNode.h
Forward DeclarationsForward Declarations Forward Declarations: Forward Declarations:
Used when defining classes that rely on Used when defining classes that rely on each other.each other.
Indicates to compiler that the class in Indicates to compiler that the class in the forward declaration is going to be the forward declaration is going to be defined later and is a valid class.defined later and is a valid class.
Similar to use of function signatures to Similar to use of function signatures to ensure compiler sees all available ensure compiler sees all available functions.functions.
Linked ListsLinked Lists
Linked List Node ConstructorLinked List Node Constructor Set Data Value, Set PointerSet Data Value, Set Pointer
ListNode<Type>::ListNode<Type>(Type ListNode<Type>::ListNode<Type>(Type inputData, ListNode<Type>* inputData, ListNode<Type>* inputLink)inputLink)
{{data = inputData;data = inputData;link = inputLink;link = inputLink;
}}
List OperationsList Operations
What operations do we want or need What operations do we want or need for the LinkedList?for the LinkedList?
ConstructorConstructor
DestructorDestructor
isEmpty()isEmpty()
isFull()isFull() // doesn’t make sense in this // doesn’t make sense in this contextcontext
add() (element?, position?)add() (element?, position?)
delete() (element?, position?)delete() (element?, position?)
Linked ListsLinked Lists
Linked List ConstructorLinked List Constructor Creates an empty listCreates an empty list Essence of list is “first” pointer, so Essence of list is “first” pointer, so
that should be set to zero if emptythat should be set to zero if empty
LinkedList<Type>::LinkedList<Type>()LinkedList<Type>::LinkedList<Type>()
{{
first = 0;first = 0;
}}
Linked List InsertionLinked List Insertion
Function Interface:Function Interface:
void add(Type & toAdd);void add(Type & toAdd);
Passed in a variable of type TypePassed in a variable of type Type
11stst step: Generate a new ListNode step: Generate a new ListNode Should hold value toAdd of type TypeShould hold value toAdd of type Type Should point to nothingShould point to nothing
Linked List InsertionLinked List Insertion
Node Creation: Node<Type> *node = new Node Creation: Node<Type> *node = new Node<Type>(toAdd, 0);Node<Type>(toAdd, 0);
Then need to insert in “right” place in list. Then need to insert in “right” place in list. What is right place?What is right place? Depends on problem of interestDepends on problem of interest Sorted list? First in, first out list?Sorted list? First in, first out list?
Let’s look at four cases:Let’s look at four cases: Empty listEmpty list Non-empty, Front of listNon-empty, Front of list Non-empty, Back of listNon-empty, Back of list Non-empty, Arbitrary position in middle of listNon-empty, Arbitrary position in middle of list
Insertion into Empty Insertion into Empty ListList
Empty ListEmpty List
FirstFirst FirstFirst
0 value 0void LinkedList:<Type>:Add(Type & toAdd)void LinkedList:<Type>:Add(Type & toAdd){{
ListNode<Type> *node = new ListNode<Type>(toAdd, 0);ListNode<Type> *node = new ListNode<Type>(toAdd, 0);if (first == 0) first = node;if (first == 0) first = node;
}}
InsertionInsertion
Non-empty list, insert at frontNon-empty list, insert at front
value1 value2 0
first
value3 0node
value1 value2 0
firstvalue3
Linked List InsertionsLinked List Insertions
Insert at front method:Insert at front method:
ListNode<Type> *node = new ListNode<Type> *node = new ListNode<Type>(toAdd, first);ListNode<Type>(toAdd, first);
first = node;first = node;
InsertionInsertion
Non-empty list, insert at backNon-empty list, insert at back
value1 value2 0
first
value3 0node
value1 value2first
value3 0
Linked List InsertionsLinked List Insertions Insert at back method: Insert at back method:
// get to last node// get to last nodeListNode<Type>* current = first;ListNode<Type>* current = first;while (current-> link != 0)while (current-> link != 0){{
current = current->link;current = current->link;}}
// add// addListNode<Type>* node = new ListNode<Type>* node = new ListNode<Type>(toAdd, ListNode<Type>(toAdd, 0);0);current->link = node;current->link = node;
InsertionInsertion
Non-empty list, insert in middleNon-empty list, insert in middle
value1 value2 0
first
value3 0node
value1 value2 0first
value3
current
Linked List InsertionsLinked List Insertions
Insert at arbitrary place:Insert at arbitrary place:
ListNode<Type>* current = first;ListNode<Type>* current = first;
while (someExpression holds)while (someExpression holds) // current->value < 5// current->value < 5
{{ // for example// for example
current = current-> link;current = current-> link;
}}
ListNode<Type>* node = ListNode<Type>* node =
new ListNode<Type>(value, current->link);new ListNode<Type>(value, current->link);
current->link = node;current->link = node;
Linked List InsertionsLinked List Insertions
Insertion at front, insertion at end usually Insertion at front, insertion at end usually encapsulated into two linked list methods:encapsulated into two linked list methods: Insert (at front), Append (onto back)Insert (at front), Append (onto back)
Insertion in middle could be encapsulated Insertion in middle could be encapsulated as insertAtNth()as insertAtNth() Usually seen instead as part of more Usually seen instead as part of more
complicated methods (insertSorted for complicated methods (insertSorted for example)example)
Linked List: DeletionLinked List: Deletion
How about deleting nodes?How about deleting nodes? Very similar to addition – 3 casesVery similar to addition – 3 cases Case 1: Delete from frontCase 1: Delete from front
value1 value2 0first
value3
value2 0value3first
Linked Lists: DeletionLinked Lists: Deletion
Deletion from front:Deletion from front:
ListNode<Type>* node = first;ListNode<Type>* node = first;
first = first->link;first = first->link;
delete node;delete node;
Linked Lists: DeletionLinked Lists: Deletion
Case 2: Delete from backCase 2: Delete from back
value1 value2 0first
value3
value3 0value1first
current
previous
Linked Lists: DeletionLinked Lists: Deletion Deletion from back:Deletion from back:
// get to just before last node// get to just before last nodeListNode<Type>* previous =0;ListNode<Type>* previous =0;ListNode<Type>* current = first;ListNode<Type>* current = first;while (current-> link != 0)while (current-> link != 0){{
previous = current;previous = current;current = current->link;current = current->link;
}}
previous->link = 0;previous->link = 0;delete current;delete current;
Linked Lists: DeletionLinked Lists: Deletion
Case 3: Delete from arbitrary Case 3: Delete from arbitrary locationlocation
value1 value2 0first
value3
value2 0value1first
current
previous
Linked Lists: DeletionsLinked Lists: Deletions
ListNode<Type>* previous =0;ListNode<Type>* previous =0;ListNode<Type>* current = first;ListNode<Type>* current = first;while (someExpression holds) //current->value != while (someExpression holds) //current->value !=
{{ // value3 for example // value3 for exampleprevious = current;previous = current;current = current->link;current = current->link;
}}
previous->link = current->link;previous->link = current->link;delete current;delete current;
IteratorsIterators
Implementing List Implementing List OperationsOperations
There are a whole slew of operations There are a whole slew of operations that rely on iterating through the that rely on iterating through the elements in a container:elements in a container: Printing all valuesPrinting all values Finding maximum and minimumFinding maximum and minimum Finding average of numbers in containerFinding average of numbers in container Finding elements that satisfy a Finding elements that satisfy a
particular propertyparticular property ……..
LinkedList IteratorLinkedList Iterator Assume we are staying within just the List and Nodes Assume we are staying within just the List and Nodes
frameworkframework We’ve used encapsulation to hide the Node data from We’ve used encapsulation to hide the Node data from
us – we can only read it through the List itself.us – we can only read it through the List itself. To implement these features that have to look at To implement these features that have to look at
every Node, we would need to add max, min, every Node, we would need to add max, min, average, … functions to the List class average, … functions to the List class
This is both unwieldy and prevents easy reuse – We This is both unwieldy and prevents easy reuse – We are putting too much domain specific information in are putting too much domain specific information in the List classthe List class
Let’s build one more class: An Let’s build one more class: An iteratoriterator: An object used : An object used to traverse the elements of a container class which to traverse the elements of a container class which also has privileged rights to read Nodesalso has privileged rights to read Nodes
Properties of List Properties of List IteratorIterator
Define a class Define a class LinkedListIterator<Type> which:LinkedListIterator<Type> which: Is a friend of both LinkedList<Type> (to Is a friend of both LinkedList<Type> (to
find the front) and ListNode<Type> (to find the front) and ListNode<Type> (to be able to read individual nodes)be able to read individual nodes)
Initialize with LinkedList<Type> object Initialize with LinkedList<Type> object it will be iterating overit will be iterating over
Define a pointer, current, in the iterator Define a pointer, current, in the iterator which is the pointer to a position in the which is the pointer to a position in the LinkedList, thus a pointer to a ListNodeLinkedList, thus a pointer to a ListNode
Define methods useful for iteration: Define methods useful for iteration:
Properties of List Properties of List IteratorIterator
Functions useful for iterating:Functions useful for iterating: notNull()notNull() // make sure not past last // make sure not past last
datadata nextNotNull() // make sure more datanextNotNull() // make sure more data first()first() // get data at front of list// get data at front of list next()next() // get data ahead one node // get data ahead one node
from currentfrom current
List Iterator ExampleList Iterator Example
List1 Data1 List1 Data2 List1 Data3
Iterator 1 -current
Iterator 2 -current
List1 Data1 List1 Data2
Iterator 3 –current (nextNotNull =false)Can have multiple iterators on
the same List (Iterators 1 and 2 here)
Iterator 3 is about to reach the end of itsList (nextNotNull is false, meaning on last node)
first
first
List Iterator DefinitionList Iterator Definitiontemplate <class Type> template <class Type> class LinkedListIteratorclass LinkedListIterator{{
public:public:LinkedListIterator(const LinkedList<Type> & inputList);LinkedListIterator(const LinkedList<Type> & inputList);bool notNull();bool notNull();bool nextNotNull();bool nextNotNull();Type* first();Type* first();Type* next();Type* next();
private:private:const LinkedList<Type>& list; // list working on const LinkedList<Type>& list; // list working on // this syntax above is a lot like storing a pointer to the // this syntax above is a lot like storing a pointer to the
listlistListNode<Type>* current; // points to a node in listListNode<Type>* current; // points to a node in list
}}
List Iterator DefinitionList Iterator Definition
Need to addNeed to addfriend class LinkedListIterator<Type> to both friend class LinkedListIterator<Type> to both LinkedList.h and ListNode.hLinkedList.h and ListNode.h
These two classes have to grant These two classes have to grant friendship to the linked list iterator.friendship to the linked list iterator.
Implementation in Implementation in LinkedListIterator.hLinkedListIterator.h
Linked List DestructorLinked List Destructor ~LinkedList() function [Destructor]~LinkedList() function [Destructor]
Need to delete all nodes in the listNeed to delete all nodes in the list
ListNode<Type>* next;ListNode<Type>* next; while (first != 0)while (first != 0) {{
next = first->link;next = first->link;delete first;delete first;first = next;first = next;
}}