SlideShare une entreprise Scribd logo
1  sur  69
Télécharger pour lire hors ligne
Linked Lists
Preliminaries
• Options for implementing an ADT List
– Array has a fixed size
• Data must be shifted during insertions and deletions
– Linked list is able to grow in size as needed
Introduction to the Linked List ADT
• A linked list is a series of connected nodes,
where each node is a data structure.
• A linked list can grow or shrink in size as the
program runs
Advantages of Linked Lists over Arrays
and vectors
• A linked list can easily grow or shrink in size.
• Insertion and deletion of nodes is quicker with
linked lists than with vectors.
4
The composition of a Linked List
• Each node in a linked list contains one or
more members that represent data.
• In addition to the data, each node contains
a pointer, which can point to another node.
5
The composition of a Linked List
• A linked list is called "linked" because each
node in the series has a pointer that points
to the next node in the list.
6
Declarations
• First you must declare a data structure that
will be used for the nodes. For example, the
following struct could be used to create
a list where each node holds a float:
7
struct ListNode
{
float value;
struct ListNode *next;
};
Declarations
• The next step is to declare a pointer to
serve as the list head, as shown below.
8
ListNode *head;
• Once you have declared a node data
structure and have created a NULL head
pointer, you have an empty linked list.
• The next step is to implement operations
with the list.
Linked List Operations
• We will use the following class declaration (on the
next slide), which is stored in FloatList.h.
9
10
class FloatList
{
private:
// Declare a structure for the list
struct ListNode
{
float value;
struct ListNode *next;
};
ListNode *head; // List head pointer
public:
FloatList(void) // Constructor
{ head = NULL; }
~FloatList(void); // Destructor
void appendNode(float);
void insertNode(float);
void deleteNode(float);
void displayList(void);
};
Appending a Node to the List
• To append a node to a linked list means to add the node to
the end of the list.
• The pseudocode is shown below. The C++ code follows.
11
Create a new node.
Store data in the new node.
If there are no nodes in the list
Make the new node the first node.
Else
Traverse the List to Find the last node.
Add the new node to the end of the list.
End If.
12
void FloatList::appendNode(float num)
{
ListNode *newNode, *nodePtr;
// Allocate a new node & store num
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
// If there are no nodes in the list
// make newNode the first node
if (!head)
head = newNode;
else // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
}
}
Program 1
13
// This program demonstrates a simple append
// operation on a linked list.
#include <iostream.h>
#include "FloatList.h”
void main(void)
{
FloatList List;
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
}
(This program displays no output.)
Stepping Through the Program
• The head pointer is declared as a global variable.
head is automatically initialized to 0 (NULL),
which indicates that the list is empty.
• The first call to appendNode passes 2.5 as the
argument. In the following statements, a new
node is allocated in memory, 2.5 is copied into its
value member, and NULL is assigned to the
node's next pointer.
14
15
newNode = new ListNode;
newNode->value = num;
newNode->next = nULL;
16
The next statement to execute is the following if statement.
if (!head)
head = newNode;
There are no more statements to execute, so control returns to function main.
17
In the second call to appendNode, 7.9 is passed as the argument. Once again, the first
three statements in the function create a new node, store the argument in the node's
value member, and assign its next pointer to NULL.
18
Since head no longer points to NULL, the else part of the if statement executes:
else // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
}
19
nodePtr is already at the end of the list, so the while loop immediately terminates.
The last statement, nodePtr->next = newNode; causes nodePtr->next to point
to the new node. This inserts newNode at the end of the list.
20
The third time appendNode is called, 12.6 is passed as the argument. Once again, the
first three statements create a node with the argument stored in the value member.
21
next, the else part of the if statement executes. As before, nodePtr is made to
point to the same node as head.
22
Since nodePtr->next is not NULL, the while loop will execute. After its first
iteration, nodePtr will point to the second node in the list.
23
The while loop's conditional test will fail after the first iteration because nodePtr-
>next now points to NULL. The last statement, nodePtr->next = newNode;
causes
nodePtr->next to point to the new node. This inserts newNode at the end of the list
The figure above depicts the final state of the linked list.
Traversing the List
• The displayList member function traverses the list,
displaying the value member of each node. The following
pseudocode represents the algorithm. The C++ code for the
member function follows on the next slide.
24
Assign List head to node pointer.
While node pointer is not NULL
Display the value member of the node pointed to by node pointer.
Assign node pointer to its own next member.
End While.
25
void FloatList::displayList(void)
{
ListNode *nodePtr;
nodePtr = head;
while (nodePtr)
{
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}
Program 2
26
// This program calls the displayList member function.
// The funcion traverses the linked list displaying
// the value stored in each node.
#include <iostream.h>
#include "FloatList.h"
void main(void)
{
FloatList List;
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
list.displayList();
}
Program 2 Output
27
2.5
7.9
12.6
Inserting a Node
• Using the listNode structure again, the
pseudocode on the next slide shows an
algorithm for finding a new node’s proper
position in the list and inserting there.
• The algorithm assumes the nodes in the list
are already in order.
28
29
Create a new node.
Store data in the new node.
If there are no nodes in the list
Make the new node the first node.
Else
Find the first node whose value is greater than or equal
the new value, or the end of the list (whichever is first).
Insert the new node before the found node, or at the end of
the list if no node was found.
End If.
30
The code for the traversal algorithm is shown below. (As before, num holds the value being
inserted into the list.)
// Initialize nodePtr to head of list
nodePtr = head;
// Skip all nodes whose value member is less
// than num.
while (nodePtr != NULL && nodePtr->value < num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
The entire insertNode function begins on the next slide.
31
void FloatList::insertNode(float num)
{
ListNode *newNode, *nodePtr, *previousNode;
// Allocate a new node & store Num
newNode = new ListNode;
newNode->value = num;
// If there are no nodes in the list
// make newNode the first node
if (!head)
{
head = newNode;
newNode->next = NULL;
}
else // Otherwise, insert newNode.
{
// Initialize nodePtr to head of list
nodePtr = head;
// Skip all nodes whose value member is less
// than num.
while (nodePtr != NULL && nodePtr->value < num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
} Continued on next slide…
32
// If the new mode is to be the 1st in the list,
// insert it before all other nodes.
if (previousNode == NULL)
{
head = newNode;
newNode-> = nodePtr;
}
else
{
previousNode->next = newNode;
newNode->next = nodePtr;
}
}
}
Continued from previous slide.
Program 3
33
// This program calls the displayList member function.
// The function traverses the linked list displaying
// the value stored in each node.
#include <iostream.h>
#include "FloatList.h”
void main(void)
{
FloatList list;
// Build the list
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
// Insert a node in the middle
// of the list.
list.insertNode(10.5);
// Dispay the list
list.displayList();
}
Program 3 Output
34
2.5
7.9
10.5
12.6
35
In insertNode, a new node is created and the function argument is copied to its value
member. Since the list already has nodes stored in it, the else part of the if statement
will execute. It begins by assigning nodePtr to head.
36
Since nodePtr is not NULL and nodePtr->value is less than num, the while loop will
iterate. During the iteration, previousNode will be made to point to the node that
nodePtr is pointing to. nodePtr will then be advanced to point to the next node.
37
Once again, the loop performs its test. Since nodePtr is not NULL and nodePtr-
>value is less than num, the loop will iterate a second time. During the second iteration,
both previousNode and nodePtr are advanced by one node in the list.
38
This time, the loop's test will fail because nodePtr is not less than num. The statements
after the loop will execute, which cause previousNode->next to point to newNode,
and
newNode->next to point to nodePtr.
If you follow the links, from the head pointer to the NULL, you will see that the nodes are
stored in the order of their value members.
Deleting a Node
• Deleting a node from a linked list requires two
steps:
– Remove the node from the list without breaking
the links created by the next pointers
– Deleting the node from memory
• The deleteNode function begins on the
next slide.
39
40
void FloatList::deleteNode(float num)
{
ListNode *nodePtr, *previousNode;
// If the list is empty, do nothing.
if (!head)
return;
// Determine if the first node is the one.
if (head->value == num)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
Continued on next slide…
41
else
{
// Initialize nodePtr to head of list
nodePtr = head;
// Skip all nodes whose value member is
// not equal to num.
while (nodePtr != NULL && nodePtr->value != num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
// Link the previous node to the node after
// nodePtr, then delete nodePtr.
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
Continued from previous slide.
Program 4
42
// This program demonstrates the deleteNode member function
#include <iostream.h>
#include "FloatList.h“
void main(void)
{
FloatList list;
// Build the list
list.appendNode(2.5);
list.appendNode(7.9);
list.appendNode(12.6);
cout << "Here are the initial values:n";
list.displayList();
cout << endl;
cout << "Now deleting the node in the middle.n";
cout << "Here are the nodes left.n";
list.deleteNode(7.9);
list.displayList();
cout << endl; Continued on next slide…
43
cout << "Now deleting the last node.n";
cout << "Here are the nodes left.n";
list.deleteNode(12.6);
list.displayList();
cout << endl;
cout << "Now deleting the only remaining node.n";
cout << "Here are the nodes left.n";
list.deleteNode(2.5);
list.displayList();
}
Continued from previous slide.
44
Program Output
Here are the initial values:
2.5
7.9
12.6
Now deleting the node in the middle.
Here are the nodes left.
2.5
12.6
Now deleting the last node.
Here are the nodes left.
2.5
Now deleting the only remaining node.
Here are the nodes left.
45
Look at the else part of the second if statement. This is where the function will perform
its action since the list is not empty, and the first node does not contain the value 7.9. Just
like insertNode, this function uses nodePtr and previousNode to traverse the list.
The while loop terminates when the value 7.9 is located. At this point, the list and the other
pointers will be in the state depicted in the figure below.
46
next, the following statement executes.
previousNode->next = nodePtr->next;
The statement above causes the links in the list to bypass the node that nodePtr points to.
Although the node still exists in memory, this removes it from the list.
The last statement uses the delete operator to complete the total deletion of the node.
Destroying the List
• The class's destructor should release all the
memory used by the list.
• It does so by stepping through the list,
deleting each node one-by-one. The code is
shown on the next slide.
47
48
FloatList::~FloatList(void)
{
ListNode *nodePtr, *nextNode;
nodePtr = head;
while (nodePtr != NULL)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
Notice the use of nextNode instead of previousNode. The nextNode pointer is used
to hold the position of the next node in the list, so it will be available after the node
pointed to by nodePtr is deleted.
A Linked List Template
49
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
template <class T>
class LinkedList
{
private:
// Declare a structure for the list
struct ListNode
{
T value;
struct ListNode *next;
};
ListNode *head; // List head pointer
Continued on next slide…
50
public:
LinkedList(void) // Constructor
{ head = NULL; }
~LinkedList(void); // Destructor
void appendNode(T);
void insertNode(T);
void deleteNode(T);
void displayList(void);
};
// appendNode appends a node containing the
// value pased into num, to the end of the list.
template <class T>
void LinkedList<T>::AppendNode(T num)
{
ListNode *newNode, *nodePtr;
// Allocate a new node & store num
newNode = new ListNode;
newNode->value = num;
newNode->next = NULL;
Continued on next slide…
51
// If there are no nodes in the list
// make newNode the first node
if (!head)
head = newNode;
else // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Find the last node in the list
while (nodePtr->next)
nodePtr = nodePtr->next;
// Insert newNode as the last node
nodePtr->next = newNode;
}
}
Continued on next slide…
52
// DisplayList shows the value
// stored in each node of the linked list
// pointed to by head.
template <class T>
void LinkedList<T>::DisplayList(void)
{
ListNode *nodePtr;
nodePtr = head;
while (nodePtr)
{
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}
Continued on next slide…
53
// The insertNode function inserts a node with
// num copied to its value member.
template <class T>
void LinkedList<T>::insertNode(T num)
{
ListNode *newNode, *nodePtr, *previousNode;
// Allocate a new node & store Num
newNode = new ListNode;
newNode->value = num;
// If there are no nodes in the list
// make newNode the first node
if (!head)
{
head = newNode;
newNode->next = NULL;
} Continued on next slide…
54
else // Otherwise, insert newNode at end
{
// Initialize nodePtr to head of list
nodePtr = head;
// Skip all nodes whose value member is less
// than num.
while (nodePtr != NULL && nodePtr->value < num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
// Insert the node after the one pointed to
// by previousNode and before the one pointed to
// by nodePtr.
previousNode->next = newNode;
newNode->next = nodePtr;
}
} Continued on next slide…
55
// The deleteNode function searches for a node
// with Num as its value. The node, if found, is
// deleted from the list and from memory.
template <class T>
void LinkedList<T>::deleteNode(T num)
{
ListNode *nodePtr, *previousNode;
// If the list is empty, do nothing.
if (!head)
return;
// Determine if the first node is the one.
if (head->value == num)
{
nodePtr = head->next;
delete head;
head = nodePtr;
} Continued on next slide…
56
else
{
// Initialize nodePtr to head of list
nodePtr = head;
// Skip all nodes whose value member is
// not equal to num.
while (nodePtr != NULL && nodePtr->value != num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
// Link the previous node to the node after
// nodePtr, then delete nodePtr.
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
Continued on next slide…
57
// Destructor
// This function deletes every node in the list.
template <class T>
LinkedList<T>::~LinkedList(void)
{
ListNode *nodePtr, *nextNode;
nodePtr = head;
while (nodePtr != NULL)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
#endif
Program 5
58
// This program demonstrates the linked list template.
#include <iostream.h>
#include "LinkedList.h“
void main(void)
{
LinkedList<int> list;
// Build the list
list.appendNode(2);
list.appendNode(4);
list.appendNode(6);
cout << "Here are the initial values:n";
list.displayList();
cout << endl;
Continued on next slide…
59
cout << "Now inserting the value 5.n";
list.insertNode(5);
cout << "Here are the nodes now.n";
list.displayList();
cout << endl;
cout << "Now deleting the last node.n";
list.deleteNode(6);
cout << "Here are the nodes left.n";
list.displayList();
}
60
Program Output
Here are the initial values:
2
4
6
Now inserting the value 5.
Here are the nodes now.
2
4
5
6
Now deleting the last node.
Here are the nodes left.
2
4
5
Variations of the Linked List
61
The Doubly-Linked List
62
Variations of the Linked List
The Circular Linked List
The STL list Container
• The list container, found in the Standard Template
Library, is a template version of a doubly linked list.
• STL lists can insert elements, or add elements to
their front quicker than vectors can, because
lists do not have to shift the other elements.
• lists are also efficient at adding elements at their
back because they have a built-in pointer to the last
element in the list (no traversal required).
63
64
Member Function Examples & Description
back cout << list.back() << endl;
The back member function returns a reference to the
last element in the list.
erase list.erase(iter);
list.erase(firstIter, lastIter)
The first example causes the list element pointed to by the iterator
iter to be removed. The second example causes all of the list
elements from firstIter to lastIter to be removed.
empty if (list.empty())
The empty member function returns true if the list is empty. If
the list has elements, it returns false.
65
Member Function Examples & Description
end iter = list.end();
end returns a bi-directional iterator to the end of the list.
front cout << list.front() << endl;
front returns a reference to the first element of the list.
insert list.insert(iter, x)
The insert member function inserts an element into the list.
The
example shown above inserts an element with the value x, just
before
the element pointed to by iter.
merge list1.merge(list2);
merge inserts all the items in list2 into list1. list1 is
expanded to accommodate the new elements plus any elements
already stored in list1. merge expects both lists to be sorted.
When list2 is inserted into list1, the elements are inserted into
their correct position, so the resulting list is also sorted.
66
Member Function Examples & Description
pop_back list.pop_back();
pop_back removes the last element of the list.
pop_front list.pop_front();
pop_front removes the first element of the list.
push_back list.push_back(x);
push_back inserts an element with value x at the end of
the list.
push_front list.push_front(x);
push_front inserts an element with value x at the beginning of
the
list.
reverse list.reverse();
reverse reverses the order in which the elements appear in the
list.
67
Member Function Examples & Description
size() Returns the number of elements in the list.
swap list1.swap(List2)
The swap member function swaps the elements stored in two
lists. For example, assuming list1 and list2 are lists, the
statement shown above will exchange the values in the two.
unique list.unique();
unique removes any element that has the same value as the
element
before it.
Program 6
68
// This program demonstrates the STL list container.
#include <iostream.h>
#include <list> // Include the list header
using namespace std; // Required by some compilers
void main(void)
{
list<int> myList;
list<int>::iterator iter;
// Add values to the list
for (int x = 0; x < 100; x += 10)
myList.push_back(x);
// Display the values
for (iter = myList.begin(); iter != myList.end(); iter++)
cout << *iter << " ";
cout << endl;
Continued on next slide…
69
// Now reverse the order of the elements
myList.reverse();
// Display the values again
for (iter = myList.begin(); iter != myList.end(); iter++)
cout << *iter << " ";
cout << endl;
}
Program Output
0 10 20 30 40 50 60 70 80 90
90 80 70 60 50 40 30 20 10 0

Contenu connexe

Tendances

linked list using c
linked list using clinked list using c
linked list using cVenkat Reddy
 
header, circular and two way linked lists
header, circular and two way linked listsheader, circular and two way linked lists
header, circular and two way linked listsstudent
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5Kumar
 
Circular linked list
Circular linked listCircular linked list
Circular linked listmaamir farooq
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked ListsAfaq Mansoor Khan
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)Durga Devi
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationProf Ansari
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Adam Mukharil Bachtiar
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
Circular linked list
Circular linked listCircular linked list
Circular linked listdchuynh
 

Tendances (20)

Linklist
LinklistLinklist
Linklist
 
linked list using c
linked list using clinked list using c
linked list using c
 
header, circular and two way linked lists
header, circular and two way linked listsheader, circular and two way linked lists
header, circular and two way linked lists
 
Linked lists a
Linked lists aLinked lists a
Linked lists a
 
Linked list
Linked listLinked list
Linked list
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5
 
Team 10
Team 10Team 10
Team 10
 
Data Structure (Double Linked List)
Data Structure (Double Linked List)Data Structure (Double Linked List)
Data Structure (Double Linked List)
 
Singly link list
Singly link listSingly link list
Singly link list
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
 
linked list
linked listlinked list
linked list
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
 
Linked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory AllocationLinked List Static and Dynamic Memory Allocation
Linked List Static and Dynamic Memory Allocation
 
Linked list
Linked listLinked list
Linked list
 
Algo>ADT list & linked list
Algo>ADT list & linked listAlgo>ADT list & linked list
Algo>ADT list & linked list
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 

En vedette

Link list(by harshit)
Link list(by harshit)Link list(by harshit)
Link list(by harshit)Harshit Jain
 
Effective Semantic Web Service Composition Framework Based on QoS
Effective Semantic Web Service Composition Framework Based on QoSEffective Semantic Web Service Composition Framework Based on QoS
Effective Semantic Web Service Composition Framework Based on QoSsethuraman R
 
Data structure
Data structureData structure
Data structuresnaya
 
Data structure
Data structureData structure
Data structureeShikshak
 
Scheduling algo(by HJ)
Scheduling algo(by HJ)Scheduling algo(by HJ)
Scheduling algo(by HJ)Harshit Jain
 
TRABAJO GRUPAL - La televisión y la escuela
TRABAJO GRUPAL - La televisión y la escuelaTRABAJO GRUPAL - La televisión y la escuela
TRABAJO GRUPAL - La televisión y la escuelapatriiei
 
Big Data As a service - Sethuonline.com | Sathyabama University Chennai
Big Data As a service - Sethuonline.com | Sathyabama University ChennaiBig Data As a service - Sethuonline.com | Sathyabama University Chennai
Big Data As a service - Sethuonline.com | Sathyabama University Chennaisethuraman R
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2Tech_MX
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureZaid Shabbir
 

En vedette (14)

Link list(by harshit)
Link list(by harshit)Link list(by harshit)
Link list(by harshit)
 
Effective Semantic Web Service Composition Framework Based on QoS
Effective Semantic Web Service Composition Framework Based on QoSEffective Semantic Web Service Composition Framework Based on QoS
Effective Semantic Web Service Composition Framework Based on QoS
 
Powerpoint.
Powerpoint.Powerpoint.
Powerpoint.
 
Planificación curricular anual
Planificación curricular anualPlanificación curricular anual
Planificación curricular anual
 
Data structure
Data structureData structure
Data structure
 
Data structure
Data structureData structure
Data structure
 
Scheduling algo(by HJ)
Scheduling algo(by HJ)Scheduling algo(by HJ)
Scheduling algo(by HJ)
 
TRABAJO GRUPAL - La televisión y la escuela
TRABAJO GRUPAL - La televisión y la escuelaTRABAJO GRUPAL - La televisión y la escuela
TRABAJO GRUPAL - La televisión y la escuela
 
Circular queues
Circular queuesCircular queues
Circular queues
 
Function in Mathematics
Function in MathematicsFunction in Mathematics
Function in Mathematics
 
Big Data As a service - Sethuonline.com | Sathyabama University Chennai
Big Data As a service - Sethuonline.com | Sathyabama University ChennaiBig Data As a service - Sethuonline.com | Sathyabama University Chennai
Big Data As a service - Sethuonline.com | Sathyabama University Chennai
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Data Structure (Stack)
Data Structure (Stack)Data Structure (Stack)
Data Structure (Stack)
 

Similaire à Linked Lists: An Introduction to the Basics

Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked listAmit Vats
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfKylaMaeGarcia1
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
Link list part 1
Link list part 1Link list part 1
Link list part 1Anaya Zafar
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxMeghaKulkarni27
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
 

Similaire à Linked Lists: An Introduction to the Basics (20)

Mi 103 linked list
Mi 103 linked listMi 103 linked list
Mi 103 linked list
 
Ch17
Ch17Ch17
Ch17
 
C Exam Help
C Exam Help C Exam Help
C Exam Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdf
 
DSModule2.pptx
DSModule2.pptxDSModule2.pptx
DSModule2.pptx
 
17 linkedlist (1)
17 linkedlist (1)17 linkedlist (1)
17 linkedlist (1)
 
Linked list
Linked listLinked list
Linked list
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
Linked list
Linked list Linked list
Linked list
 
Linkedlist
LinkedlistLinkedlist
Linkedlist
 
Savitch ch 13
Savitch ch 13Savitch ch 13
Savitch ch 13
 
Link list part 1
Link list part 1Link list part 1
Link list part 1
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptx
 
Savitch Ch 13
Savitch Ch 13Savitch Ch 13
Savitch Ch 13
 
Dounly linked list
Dounly linked listDounly linked list
Dounly linked list
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Cpp lernaufgabe linked_list
Cpp lernaufgabe linked_listCpp lernaufgabe linked_list
Cpp lernaufgabe linked_list
 
Linked List.pptx
Linked List.pptxLinked List.pptx
Linked List.pptx
 

Plus de Muhazzab Chouhadry

Plus de Muhazzab Chouhadry (6)

Install guid to SQL server 2008
Install guid to SQL server 2008Install guid to SQL server 2008
Install guid to SQL server 2008
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
 
Data Structure Sorting
Data Structure SortingData Structure Sorting
Data Structure Sorting
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Sentence and its types
Sentence and its typesSentence and its types
Sentence and its types
 

Dernier

Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxAvaniJani1
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEMISSRITIMABIOLOGYEXP
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfChristalin Nelson
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...HetalPathak10
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 

Dernier (20)

Comparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptxComparative Literature in India by Amiya dev.pptx
Comparative Literature in India by Amiya dev.pptx
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
Mattingly "AI & Prompt Design" - Introduction to Machine Learning"
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFEPART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
PART 1 - CHAPTER 1 - CELL THE FUNDAMENTAL UNIT OF LIFE
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
DBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdfDBMSArchitecture_QueryProcessingandOptimization.pdf
DBMSArchitecture_QueryProcessingandOptimization.pdf
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
Satirical Depths - A Study of Gabriel Okara's Poem - 'You Laughed and Laughed...
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 

Linked Lists: An Introduction to the Basics

  • 2. Preliminaries • Options for implementing an ADT List – Array has a fixed size • Data must be shifted during insertions and deletions – Linked list is able to grow in size as needed
  • 3. Introduction to the Linked List ADT • A linked list is a series of connected nodes, where each node is a data structure. • A linked list can grow or shrink in size as the program runs
  • 4. Advantages of Linked Lists over Arrays and vectors • A linked list can easily grow or shrink in size. • Insertion and deletion of nodes is quicker with linked lists than with vectors. 4
  • 5. The composition of a Linked List • Each node in a linked list contains one or more members that represent data. • In addition to the data, each node contains a pointer, which can point to another node. 5
  • 6. The composition of a Linked List • A linked list is called "linked" because each node in the series has a pointer that points to the next node in the list. 6
  • 7. Declarations • First you must declare a data structure that will be used for the nodes. For example, the following struct could be used to create a list where each node holds a float: 7 struct ListNode { float value; struct ListNode *next; };
  • 8. Declarations • The next step is to declare a pointer to serve as the list head, as shown below. 8 ListNode *head; • Once you have declared a node data structure and have created a NULL head pointer, you have an empty linked list. • The next step is to implement operations with the list.
  • 9. Linked List Operations • We will use the following class declaration (on the next slide), which is stored in FloatList.h. 9
  • 10. 10 class FloatList { private: // Declare a structure for the list struct ListNode { float value; struct ListNode *next; }; ListNode *head; // List head pointer public: FloatList(void) // Constructor { head = NULL; } ~FloatList(void); // Destructor void appendNode(float); void insertNode(float); void deleteNode(float); void displayList(void); };
  • 11. Appending a Node to the List • To append a node to a linked list means to add the node to the end of the list. • The pseudocode is shown below. The C++ code follows. 11 Create a new node. Store data in the new node. If there are no nodes in the list Make the new node the first node. Else Traverse the List to Find the last node. Add the new node to the end of the list. End If.
  • 12. 12 void FloatList::appendNode(float num) { ListNode *newNode, *nodePtr; // Allocate a new node & store num newNode = new ListNode; newNode->value = num; newNode->next = NULL; // If there are no nodes in the list // make newNode the first node if (!head) head = newNode; else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; } }
  • 13. Program 1 13 // This program demonstrates a simple append // operation on a linked list. #include <iostream.h> #include "FloatList.h” void main(void) { FloatList List; list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); } (This program displays no output.)
  • 14. Stepping Through the Program • The head pointer is declared as a global variable. head is automatically initialized to 0 (NULL), which indicates that the list is empty. • The first call to appendNode passes 2.5 as the argument. In the following statements, a new node is allocated in memory, 2.5 is copied into its value member, and NULL is assigned to the node's next pointer. 14
  • 15. 15 newNode = new ListNode; newNode->value = num; newNode->next = nULL;
  • 16. 16 The next statement to execute is the following if statement. if (!head) head = newNode; There are no more statements to execute, so control returns to function main.
  • 17. 17 In the second call to appendNode, 7.9 is passed as the argument. Once again, the first three statements in the function create a new node, store the argument in the node's value member, and assign its next pointer to NULL.
  • 18. 18 Since head no longer points to NULL, the else part of the if statement executes: else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; }
  • 19. 19 nodePtr is already at the end of the list, so the while loop immediately terminates. The last statement, nodePtr->next = newNode; causes nodePtr->next to point to the new node. This inserts newNode at the end of the list.
  • 20. 20 The third time appendNode is called, 12.6 is passed as the argument. Once again, the first three statements create a node with the argument stored in the value member.
  • 21. 21 next, the else part of the if statement executes. As before, nodePtr is made to point to the same node as head.
  • 22. 22 Since nodePtr->next is not NULL, the while loop will execute. After its first iteration, nodePtr will point to the second node in the list.
  • 23. 23 The while loop's conditional test will fail after the first iteration because nodePtr- >next now points to NULL. The last statement, nodePtr->next = newNode; causes nodePtr->next to point to the new node. This inserts newNode at the end of the list The figure above depicts the final state of the linked list.
  • 24. Traversing the List • The displayList member function traverses the list, displaying the value member of each node. The following pseudocode represents the algorithm. The C++ code for the member function follows on the next slide. 24 Assign List head to node pointer. While node pointer is not NULL Display the value member of the node pointed to by node pointer. Assign node pointer to its own next member. End While.
  • 25. 25 void FloatList::displayList(void) { ListNode *nodePtr; nodePtr = head; while (nodePtr) { cout << nodePtr->value << endl; nodePtr = nodePtr->next; } }
  • 26. Program 2 26 // This program calls the displayList member function. // The funcion traverses the linked list displaying // the value stored in each node. #include <iostream.h> #include "FloatList.h" void main(void) { FloatList List; list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); list.displayList(); }
  • 28. Inserting a Node • Using the listNode structure again, the pseudocode on the next slide shows an algorithm for finding a new node’s proper position in the list and inserting there. • The algorithm assumes the nodes in the list are already in order. 28
  • 29. 29 Create a new node. Store data in the new node. If there are no nodes in the list Make the new node the first node. Else Find the first node whose value is greater than or equal the new value, or the end of the list (whichever is first). Insert the new node before the found node, or at the end of the list if no node was found. End If.
  • 30. 30 The code for the traversal algorithm is shown below. (As before, num holds the value being inserted into the list.) // Initialize nodePtr to head of list nodePtr = head; // Skip all nodes whose value member is less // than num. while (nodePtr != NULL && nodePtr->value < num) { previousNode = nodePtr; nodePtr = nodePtr->next; } The entire insertNode function begins on the next slide.
  • 31. 31 void FloatList::insertNode(float num) { ListNode *newNode, *nodePtr, *previousNode; // Allocate a new node & store Num newNode = new ListNode; newNode->value = num; // If there are no nodes in the list // make newNode the first node if (!head) { head = newNode; newNode->next = NULL; } else // Otherwise, insert newNode. { // Initialize nodePtr to head of list nodePtr = head; // Skip all nodes whose value member is less // than num. while (nodePtr != NULL && nodePtr->value < num) { previousNode = nodePtr; nodePtr = nodePtr->next; } Continued on next slide…
  • 32. 32 // If the new mode is to be the 1st in the list, // insert it before all other nodes. if (previousNode == NULL) { head = newNode; newNode-> = nodePtr; } else { previousNode->next = newNode; newNode->next = nodePtr; } } } Continued from previous slide.
  • 33. Program 3 33 // This program calls the displayList member function. // The function traverses the linked list displaying // the value stored in each node. #include <iostream.h> #include "FloatList.h” void main(void) { FloatList list; // Build the list list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); // Insert a node in the middle // of the list. list.insertNode(10.5); // Dispay the list list.displayList(); }
  • 35. 35 In insertNode, a new node is created and the function argument is copied to its value member. Since the list already has nodes stored in it, the else part of the if statement will execute. It begins by assigning nodePtr to head.
  • 36. 36 Since nodePtr is not NULL and nodePtr->value is less than num, the while loop will iterate. During the iteration, previousNode will be made to point to the node that nodePtr is pointing to. nodePtr will then be advanced to point to the next node.
  • 37. 37 Once again, the loop performs its test. Since nodePtr is not NULL and nodePtr- >value is less than num, the loop will iterate a second time. During the second iteration, both previousNode and nodePtr are advanced by one node in the list.
  • 38. 38 This time, the loop's test will fail because nodePtr is not less than num. The statements after the loop will execute, which cause previousNode->next to point to newNode, and newNode->next to point to nodePtr. If you follow the links, from the head pointer to the NULL, you will see that the nodes are stored in the order of their value members.
  • 39. Deleting a Node • Deleting a node from a linked list requires two steps: – Remove the node from the list without breaking the links created by the next pointers – Deleting the node from memory • The deleteNode function begins on the next slide. 39
  • 40. 40 void FloatList::deleteNode(float num) { ListNode *nodePtr, *previousNode; // If the list is empty, do nothing. if (!head) return; // Determine if the first node is the one. if (head->value == num) { nodePtr = head->next; delete head; head = nodePtr; } Continued on next slide…
  • 41. 41 else { // Initialize nodePtr to head of list nodePtr = head; // Skip all nodes whose value member is // not equal to num. while (nodePtr != NULL && nodePtr->value != num) { previousNode = nodePtr; nodePtr = nodePtr->next; } // Link the previous node to the node after // nodePtr, then delete nodePtr. previousNode->next = nodePtr->next; delete nodePtr; } } Continued from previous slide.
  • 42. Program 4 42 // This program demonstrates the deleteNode member function #include <iostream.h> #include "FloatList.h“ void main(void) { FloatList list; // Build the list list.appendNode(2.5); list.appendNode(7.9); list.appendNode(12.6); cout << "Here are the initial values:n"; list.displayList(); cout << endl; cout << "Now deleting the node in the middle.n"; cout << "Here are the nodes left.n"; list.deleteNode(7.9); list.displayList(); cout << endl; Continued on next slide…
  • 43. 43 cout << "Now deleting the last node.n"; cout << "Here are the nodes left.n"; list.deleteNode(12.6); list.displayList(); cout << endl; cout << "Now deleting the only remaining node.n"; cout << "Here are the nodes left.n"; list.deleteNode(2.5); list.displayList(); } Continued from previous slide.
  • 44. 44 Program Output Here are the initial values: 2.5 7.9 12.6 Now deleting the node in the middle. Here are the nodes left. 2.5 12.6 Now deleting the last node. Here are the nodes left. 2.5 Now deleting the only remaining node. Here are the nodes left.
  • 45. 45 Look at the else part of the second if statement. This is where the function will perform its action since the list is not empty, and the first node does not contain the value 7.9. Just like insertNode, this function uses nodePtr and previousNode to traverse the list. The while loop terminates when the value 7.9 is located. At this point, the list and the other pointers will be in the state depicted in the figure below.
  • 46. 46 next, the following statement executes. previousNode->next = nodePtr->next; The statement above causes the links in the list to bypass the node that nodePtr points to. Although the node still exists in memory, this removes it from the list. The last statement uses the delete operator to complete the total deletion of the node.
  • 47. Destroying the List • The class's destructor should release all the memory used by the list. • It does so by stepping through the list, deleting each node one-by-one. The code is shown on the next slide. 47
  • 48. 48 FloatList::~FloatList(void) { ListNode *nodePtr, *nextNode; nodePtr = head; while (nodePtr != NULL) { nextNode = nodePtr->next; delete nodePtr; nodePtr = nextNode; } } Notice the use of nextNode instead of previousNode. The nextNode pointer is used to hold the position of the next node in the list, so it will be available after the node pointed to by nodePtr is deleted.
  • 49. A Linked List Template 49 #ifndef LINKEDLIST_H #define LINKEDLIST_H template <class T> class LinkedList { private: // Declare a structure for the list struct ListNode { T value; struct ListNode *next; }; ListNode *head; // List head pointer Continued on next slide…
  • 50. 50 public: LinkedList(void) // Constructor { head = NULL; } ~LinkedList(void); // Destructor void appendNode(T); void insertNode(T); void deleteNode(T); void displayList(void); }; // appendNode appends a node containing the // value pased into num, to the end of the list. template <class T> void LinkedList<T>::AppendNode(T num) { ListNode *newNode, *nodePtr; // Allocate a new node & store num newNode = new ListNode; newNode->value = num; newNode->next = NULL; Continued on next slide…
  • 51. 51 // If there are no nodes in the list // make newNode the first node if (!head) head = newNode; else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Find the last node in the list while (nodePtr->next) nodePtr = nodePtr->next; // Insert newNode as the last node nodePtr->next = newNode; } } Continued on next slide…
  • 52. 52 // DisplayList shows the value // stored in each node of the linked list // pointed to by head. template <class T> void LinkedList<T>::DisplayList(void) { ListNode *nodePtr; nodePtr = head; while (nodePtr) { cout << nodePtr->value << endl; nodePtr = nodePtr->next; } } Continued on next slide…
  • 53. 53 // The insertNode function inserts a node with // num copied to its value member. template <class T> void LinkedList<T>::insertNode(T num) { ListNode *newNode, *nodePtr, *previousNode; // Allocate a new node & store Num newNode = new ListNode; newNode->value = num; // If there are no nodes in the list // make newNode the first node if (!head) { head = newNode; newNode->next = NULL; } Continued on next slide…
  • 54. 54 else // Otherwise, insert newNode at end { // Initialize nodePtr to head of list nodePtr = head; // Skip all nodes whose value member is less // than num. while (nodePtr != NULL && nodePtr->value < num) { previousNode = nodePtr; nodePtr = nodePtr->next; } // Insert the node after the one pointed to // by previousNode and before the one pointed to // by nodePtr. previousNode->next = newNode; newNode->next = nodePtr; } } Continued on next slide…
  • 55. 55 // The deleteNode function searches for a node // with Num as its value. The node, if found, is // deleted from the list and from memory. template <class T> void LinkedList<T>::deleteNode(T num) { ListNode *nodePtr, *previousNode; // If the list is empty, do nothing. if (!head) return; // Determine if the first node is the one. if (head->value == num) { nodePtr = head->next; delete head; head = nodePtr; } Continued on next slide…
  • 56. 56 else { // Initialize nodePtr to head of list nodePtr = head; // Skip all nodes whose value member is // not equal to num. while (nodePtr != NULL && nodePtr->value != num) { previousNode = nodePtr; nodePtr = nodePtr->next; } // Link the previous node to the node after // nodePtr, then delete nodePtr. previousNode->next = nodePtr->next; delete nodePtr; } } Continued on next slide…
  • 57. 57 // Destructor // This function deletes every node in the list. template <class T> LinkedList<T>::~LinkedList(void) { ListNode *nodePtr, *nextNode; nodePtr = head; while (nodePtr != NULL) { nextNode = nodePtr->next; delete nodePtr; nodePtr = nextNode; } } #endif
  • 58. Program 5 58 // This program demonstrates the linked list template. #include <iostream.h> #include "LinkedList.h“ void main(void) { LinkedList<int> list; // Build the list list.appendNode(2); list.appendNode(4); list.appendNode(6); cout << "Here are the initial values:n"; list.displayList(); cout << endl; Continued on next slide…
  • 59. 59 cout << "Now inserting the value 5.n"; list.insertNode(5); cout << "Here are the nodes now.n"; list.displayList(); cout << endl; cout << "Now deleting the last node.n"; list.deleteNode(6); cout << "Here are the nodes left.n"; list.displayList(); }
  • 60. 60 Program Output Here are the initial values: 2 4 6 Now inserting the value 5. Here are the nodes now. 2 4 5 6 Now deleting the last node. Here are the nodes left. 2 4 5
  • 61. Variations of the Linked List 61 The Doubly-Linked List
  • 62. 62 Variations of the Linked List The Circular Linked List
  • 63. The STL list Container • The list container, found in the Standard Template Library, is a template version of a doubly linked list. • STL lists can insert elements, or add elements to their front quicker than vectors can, because lists do not have to shift the other elements. • lists are also efficient at adding elements at their back because they have a built-in pointer to the last element in the list (no traversal required). 63
  • 64. 64 Member Function Examples & Description back cout << list.back() << endl; The back member function returns a reference to the last element in the list. erase list.erase(iter); list.erase(firstIter, lastIter) The first example causes the list element pointed to by the iterator iter to be removed. The second example causes all of the list elements from firstIter to lastIter to be removed. empty if (list.empty()) The empty member function returns true if the list is empty. If the list has elements, it returns false.
  • 65. 65 Member Function Examples & Description end iter = list.end(); end returns a bi-directional iterator to the end of the list. front cout << list.front() << endl; front returns a reference to the first element of the list. insert list.insert(iter, x) The insert member function inserts an element into the list. The example shown above inserts an element with the value x, just before the element pointed to by iter. merge list1.merge(list2); merge inserts all the items in list2 into list1. list1 is expanded to accommodate the new elements plus any elements already stored in list1. merge expects both lists to be sorted. When list2 is inserted into list1, the elements are inserted into their correct position, so the resulting list is also sorted.
  • 66. 66 Member Function Examples & Description pop_back list.pop_back(); pop_back removes the last element of the list. pop_front list.pop_front(); pop_front removes the first element of the list. push_back list.push_back(x); push_back inserts an element with value x at the end of the list. push_front list.push_front(x); push_front inserts an element with value x at the beginning of the list. reverse list.reverse(); reverse reverses the order in which the elements appear in the list.
  • 67. 67 Member Function Examples & Description size() Returns the number of elements in the list. swap list1.swap(List2) The swap member function swaps the elements stored in two lists. For example, assuming list1 and list2 are lists, the statement shown above will exchange the values in the two. unique list.unique(); unique removes any element that has the same value as the element before it.
  • 68. Program 6 68 // This program demonstrates the STL list container. #include <iostream.h> #include <list> // Include the list header using namespace std; // Required by some compilers void main(void) { list<int> myList; list<int>::iterator iter; // Add values to the list for (int x = 0; x < 100; x += 10) myList.push_back(x); // Display the values for (iter = myList.begin(); iter != myList.end(); iter++) cout << *iter << " "; cout << endl; Continued on next slide…
  • 69. 69 // Now reverse the order of the elements myList.reverse(); // Display the values again for (iter = myList.begin(); iter != myList.end(); iter++) cout << *iter << " "; cout << endl; } Program Output 0 10 20 30 40 50 60 70 80 90 90 80 70 60 50 40 30 20 10 0