Presentation is loading. Please wait.

Presentation is loading. Please wait.

Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists.

Similar presentations


Presentation on theme: "Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists."— Presentation transcript:

1 Linked List Containers

2 Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists of Data Data Pointer to another node Pointer to another node Traditional view of data: Traditional view of data: Data

3 Linked Lists Insertion at a specific point: Get a new node (allocate from memory) Set data pointer Set link of new node to previous node link Set link of previous node link to new node FATMATRAT HAT

4 Linked Lists Deletion at a specific point: Set the link of the previous node to the link of the node to delete. FATMATRAT FATRAT

5 Linked List Representations Can locate data in any place in memory, not required to be sequential Can locate data in any place in memory, not required to be sequential No requirements on computing size of list beforehand No requirements on computing size of list beforehand No more space than need No more space than need No bounds on space No bounds on space No resizing No resizing Still fairly trivial to manage and understand Still fairly trivial to manage and understand

6 Linked Lists in C++ Need to define a ListNode Class that represents: Need to define a ListNode Class that represents: Data Data Pointer to another ListNode Pointer to another ListNode Need to define a LinkedList Class that provides container operations (Add, Delete, etc), using ListNodes to implement the storage for the container Need to define a LinkedList Class that provides container operations (Add, Delete, etc), using ListNodes to implement the storage for the container

7 Linked Lists in C++ Node definition: Node definition: class nodeName class ThreeLetterListNode {{ private: private: type dataName; char data[3]; nodeName *link; ThreeLetterListNode * link; }}

8 Linked Lists in C++ Requirements for LinkedList construct: Requirements for LinkedList construct: Want to preserve encapsulation of nodes and ensure that updating the data and link pointers are only accomplished by the ListNode itself or the LinkedList Want to preserve encapsulation of nodes and ensure that updating the data and link pointers are only accomplished by the ListNode itself or the LinkedList Arbitrary and unlimited amount of memory Arbitrary and unlimited amount of memory Characterize the LinkedList as: A LinkedList consists of zero or more objects of type ListNode. Characterize the LinkedList as: A LinkedList consists of zero or more objects of type ListNode.

9 Linked Lists Linked List definition suggests that the List object actually physically contains lots of ListNodes. Linked List definition suggests that the List object actually physically contains lots of ListNodes. Contains a pointer, called first, to one ListNode, from which the rest of the ListNodes can be found by following links. Contains a pointer, called first, to one ListNode, from which the rest of the ListNodes can be found by following links. All ListNode objects are not physically contained within the LinkedList object All ListNode objects are not physically contained within the LinkedList object To access private data members of ListNode class, without making the data members public or having public functions to set data and links, To access private data members of ListNode class, without making the data members public or having public functions to set data and links, make the LinkedList class a friend of the ListNode class: make the LinkedList class a friend of the ListNode class:

10 Linked Lists class LinkedList; // forward declaration template template class ListNode { friend class LinkedList ; private: Type data; Type data; ListNode *link; ListNode *link;}; template template class LinkedList { public: // manipulation operations public: // manipulation operations private: private: ListNode *first; } LinkedList.h ListNode.h

11 Forward Declarations Forward Declarations: Forward Declarations: Used when defining classes that rely on each other. Used when defining classes that rely on each other. Indicates to compiler that the class in the forward declaration is going to be defined later and is a valid class. Indicates to compiler that the class in the forward declaration is going to be defined later and is a valid class. Similar to use of function signatures to ensure compiler sees all available functions. Similar to use of function signatures to ensure compiler sees all available functions.

12 Linked Lists Linked List Node Constructor Linked List Node Constructor Set Data Value, Set Pointer Set Data Value, Set Pointer ListNode ::ListNode (Type inputData, ListNode * inputLink) { data = inputData; link = inputLink; }

13 List Operations What operations do we want or need for the LinkedList? What operations do we want or need for the LinkedList?ConstructorDestructorisEmpty() isFull()// doesn’t make sense in this context add() (element?, position?) delete() (element?, position?)

14 Linked Lists Linked List Constructor Linked List Constructor Creates an empty list Creates an empty list Essence of list is “first” pointer, so that should be set to zero if empty Essence of list is “first” pointer, so that should be set to zero if emptyLinkedList<Type>::LinkedList<Type>(){ first = 0; }

15 Linked List Insertion Function Interface: void add(Type & toAdd); Passed in a variable of type Type 1 st step: Generate a new ListNode 1 st step: Generate a new ListNode Should hold value toAdd of type Type Should hold value toAdd of type Type Should point to nothing Should point to nothing

16 Linked List Insertion Node Creation: Node *node = new Node (toAdd, 0); Node Creation: Node *node = new Node (toAdd, 0); Then need to insert in “right” place in list. What is right place? Then need to insert in “right” place in list. What is right place? Depends on problem of interest Depends 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 list Empty list Non-empty, Front of list Non-empty, Front of list Non-empty, Back of list Non-empty, Back of list Non-empty, Arbitrary position in middle of list Non-empty, Arbitrary position in middle of list

17 Insertion into Empty List Insertion into Empty List Empty List Empty List FirstFirst 0 value0 void LinkedList: :Add(Type & toAdd) { ListNode *node = new ListNode (toAdd, 0); if (first == 0) first = node; }

18 Insertion Non-empty list, insert at front Non-empty list, insert at front value1value20 first value30 node value1value20 first value3

19 Linked List Insertions Insert at front method: Insert at front method: ListNode *node = new ListNode (toAdd, first); first = node;

20 Insertion Non-empty list, insert at back Non-empty list, insert at back value1value20 first value30 node value1value2 first value30

21 Linked List Insertions Insert at back method: Insert at back method: // get to last node ListNode * current = first; while (current-> link != 0) { current = current->link; } // add ListNode * node = new ListNode (toAdd, 0); current->link = node;

22 Insertion Non-empty list, insert in middle Non-empty list, insert in middle value1value20 first value30 node value1value20 first value3 current

23 Linked List Insertions Insert at arbitrary place: Insert at arbitrary place: ListNode * current = first; while (someExpression holds)// current->value value < 5 {// for example current = current-> link; } ListNode * node = new ListNode (value, current->link); current->link = node;

24 Linked List Insertions Insertion at front, insertion at end usually encapsulated into two linked list methods: Insertion at front, insertion at end usually encapsulated into two linked list methods: Insert (at front), Append (onto back) Insert (at front), Append (onto back) Insertion in middle could be encapsulated as insertAtNth() Insertion in middle could be encapsulated as insertAtNth() Usually seen instead as part of more complicated methods (insertSorted for example) Usually seen instead as part of more complicated methods (insertSorted for example)

25 Linked List: Deletion How about deleting nodes? How about deleting nodes? Very similar to addition – 3 cases Very similar to addition – 3 cases Case 1: Delete from front Case 1: Delete from front value1value20 first value3 value20value3 first

26 Linked Lists: Deletion Deletion from front: Deletion from front: ListNode * node = first; first = first->link; delete node;

27 Linked Lists: Deletion Case 2: Delete from back Case 2: Delete from back value1value20 first value3 0value1 first current previous

28 Linked Lists: Deletion Deletion from back: Deletion from back: // get to just before last node ListNode * previous =0; ListNode * current = first; while (current-> link != 0) { previous = current; current = current->link; } previous->link = 0; delete current;

29 Linked Lists: Deletion Case 3: Delete from arbitrary location Case 3: Delete from arbitrary location value1value20 first value3 value20value1 first current previous

30 Linked Lists: Deletions ListNode * previous =0; ListNode * current = first; while (someExpression holds) //current->value != { // value3 for example previous = current; current = current->link; } previous->link = current->link; delete current;

31 Iterators

32 Implementing List Operations There are a whole slew of operations that rely on iterating through the elements in a container: There are a whole slew of operations that rely on iterating through the elements in a container: Printing all values Printing all values Finding maximum and minimum Finding maximum and minimum Finding average of numbers in container Finding average of numbers in container Finding elements that satisfy a particular property Finding elements that satisfy a particular property …. ….

33 LinkedList Iterator Assume we are staying within just the List and Nodes framework Assume we are staying within just the List and Nodes framework We’ve used encapsulation to hide the Node data from us – we can only read it through the List itself. We’ve used encapsulation to hide the Node data from us – we can only read it through the List itself. To implement these features that have to look at every Node, we would need to add max, min, average, … functions to the List class To implement these features that have to look at every Node, we would need to add max, min, average, … functions to the List class This is both unwieldy and prevents easy reuse – We are putting too much domain specific information in the List class This is both unwieldy and prevents easy reuse – We are putting too much domain specific information in the List class Let’s build one more class: An iterator : An object used to traverse the elements of a container class which also has privileged rights to read Nodes Let’s build one more class: An iterator : An object used to traverse the elements of a container class which also has privileged rights to read Nodes

34 Properties of List Iterator Define a class LinkedListIterator which: Define a class LinkedListIterator which: Is a friend of both LinkedList (to find the front) and ListNode (to be able to read individual nodes) Is a friend of both LinkedList (to find the front) and ListNode (to be able to read individual nodes) Initialize with LinkedList object it will be iterating over Initialize with LinkedList object it will be iterating over Define a pointer, current, in the iterator which is the pointer to a position in the LinkedList, thus a pointer to a ListNode Define a pointer, current, in the iterator which is the pointer to a position in the LinkedList, thus a pointer to a ListNode Define methods useful for iteration: Define methods useful for iteration:

35 Properties of List Iterator Functions useful for iterating: Functions useful for iterating: notNull() // make sure not past last data notNull() // make sure not past last data nextNotNull() // make sure more data nextNotNull() // make sure more data first()// get data at front of list first()// get data at front of list next()// get data ahead one node from current next()// get data ahead one node from current

36 List Iterator Example List1 Data1List1 Data2List1 Data3 Iterator 1 -current Iterator 2 -current List1 Data1List1 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 its List (nextNotNull is false, meaning on last node) first

37 List Iterator Definition template template class LinkedListIterator {public: LinkedListIterator(const LinkedList & inputList); bool notNull(); bool nextNotNull(); Type* first(); Type* next(); private: const LinkedList & list; // list working on // this syntax above is a lot like storing a pointer to the list ListNode * current; // points to a node in list }

38 List Iterator Definition Need to add Need to add friend class LinkedListIterator to both LinkedList.h and ListNode.h These two classes have to grant friendship to the linked list iterator. Implementation in LinkedListIterator.h Implementation in LinkedListIterator.h

39 Linked List Destructor ~LinkedList() function [Destructor] ~LinkedList() function [Destructor] Need to delete all nodes in the list ListNode * next; ListNode * next; while (first != 0) while (first != 0) { next = first->link; delete first; first = next; }


Download ppt "Linked List Containers. Linked Lists List consists of multiple listnodes List consists of multiple listnodes Each listnode consists of Each listnode consists."

Similar presentations


Ads by Google