Escolar Documentos
Profissional Documentos
Cultura Documentos
Linked Lists
(Part 3)
Objectives
By the end of this lesson, you will be able to:
Improve implementation of some operations on
linked lists
Create an abstract linked list type using C++
templates
CT077-3-2-DSTR
Data Structures
Improving Operations
Inserting a new item at beginning of a linked list is
fast (no traversal required)
X
X
lastNode
newNode
newNode
CT077-3-2-DSTR
Data Structures
Improving Operations
If in a program there is a need to frequently insert
items at end of the list, its worth to change the data
structure to allow more efficient implementation
class LinkedList {
public:
NodeType* head;
NodeType* tail;
int size;
// .. the other implemented
methods
};
CT077-3-2-DSTR
Data Structures
X
5
CT077-3-2-DSTR
newNode
Data Structures
CT077-3-2-DSTR
Data Structures
Necessary Modifications
For example, the constructor will be modified to:
Inserting a new item at
the beginning of a list
will affect the tail ONLY
if the list was empty
CT077-3-2-DSTR
LinkedList(){
this->size = 0;
this->head= NULL;
this->tail= NULL;
}
void insertAtBeginning(int
value){
NodeType * newNode= new
NodeType;
newNode->info = value;
newNode->link = head;
head = newNode;
size++;
if(tail == NULL)
tail = newNode;
}
Data Structures
Necessary Modifications
deleteFirst() should also be changed
Deleting first item in the list will affect tail ONLY if
the list becomes empty after deletion
void deleteFirst(){
if(size > 0){//else, may want to give a message or
error
NodeType * toBeDeleted = head;
head = head->link;
delete toBeDeleted;
size--;
if(head == NULL)
tail = NULL;
}
}
CT077-3-2-DSTR
Data Structures
beforeLast
Data Structures
class LinkedList {
public:
NodeType* head;
NodeType* tail;
int size;
};
class DoubleLinkedList {
public:
DoubleNode* head;
DoubleNode* tail;
int size;
};
class DoubleNode {
public:
double info;
DoubleNode*
link;
};
CT077-3-2-DSTR
Data Structures
10
Data Structures
11
Data Structures
12
Data Structures
13
Data Structures
14
CT077-3-2-DSTR
Data Structures
15
CT077-3-2-DSTR
Data Structures
16
Data Structures
17
Data Structures
18
Data Structures
19
Homework
Using C++ Templates, modify the implementation of
LinkeList and NodeType classes to be generic
Change info to be of template type T instead of integer
Apply all necessary changes to the implemented methods
Data Structures
20
CT077-3-2-DSTR
Data Structures
21