0% found this document useful (0 votes)
16 views

Lecture 4 Singly Linked List

Uploaded by

r.arshadr12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lecture 4 Singly Linked List

Uploaded by

r.arshadr12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

Data Structures & Algorithms

 Lecture 5: Singly Linked List

 Dr. Farzana Jabeen

 Department Of Computing (DOC),


 School of Electrical Engineering & Computer Science (SEECS),
 National University of Sciences & Technology (NUST)

Data Structures & Algorithms Lecture 4: Linked Lists


Data Structures & Algorithms

Lecture 5: Singly Linked List

Dr. Farzana Jabeen

Department Of Computing (DOC),


School of Electrical Engineering & Computer Science (SEECS),
National University of Sciences & Technology (NUST)

*Courtesy: Dr. Asalan Ahmad and Dr. Yasir Faheem

26/06/2023
Linked List Operations

 Creating the list


► Initialize pointers to NULL;
 Inserting nodes
► Insert at beginning
► Insert at middle

► Insert at last

 Deleting nodes
► Delete from beginning, middle, last
 Traversing the list
 Searching a specified item in the list
 Destroying the list

Data Structures & Algorithms Lecture 4: Linked Lists


Introduction to the Linked List
ADT

• A linked list is a series of connected nodes, where each

node is a data structure.

• Linear relationship between elements:

1. Each element except the first one has a predecessor.

2. Each element except the last one has a successor.

• Length: the number of items in the list.


Data Structures & Algorithms Lecture 4: Linked Lists
Singly Linked
List
• Simplest form of 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.

Data Structures & Algorithms Lecture 4: Linked Lists


The composition of a Linked

• A linked list is called "linked" because each


node in the series has a pointer that points to
the next node in the list.

Data Structures & Algorithms Lecture 4: Linked Lists


Singly Linked Lists

head

next next next next

a b c d

First node Last node

Data Structures & Algorithms Lecture 4: Linked Lists


Empty List

 Empty Linked list is a single pointer having the value


of NULL.

head = NULL;

head

Data Structures & Algorithms Lecture 4: Linked Lists


Basic Ideas

 Let’s assume that the node is given by the following type


declaration:
struct Node {
Object element;
Node *next;
};
……………………………………………………………………………………..
Class Node {
Int Data;
Node *next;

}
Data Structures & Algorithms Lecture 4: Linked Lists
Linked list data 5

structure
•One of the attributes of a linked list is that there is not a physical
relationship between the nodes; that is, they are not stored contiguously in

memory (unlike array elements)

•To determine the beginning of the list, and each additional element in the

list, we need to use pointers.

Data Structures & Algorithms Lecture 4: Linked Lists


Linked list data 6

structure

⚫The pointer to the first node in the list is referred to as the head
pointer, because it points to the head node in the list

⚫In addition to the head pointer, there are usually other pointers associated

with the list. These can include a pointer to the last element in the list (tail

pointer) and a pointer that traverses the list to find data (navigator or

traversal pointer)

Data Structures & Algorithms Lecture 4: Linked Lists


Linked List

Data Structures & Algorithms Lecture 4: Linked Lists


Linked List

Data Structures & Algorithms Lecture 4: Linked Lists


Linked List Example (Simple)
// allocate 3 nodes in the heap
// Linked list implementation in C++
one = new Node();
#include <iostream>
two = new Node();
using namespace std;
three = new Node();

// Creating a node // Assign value values

class Node { one->value = 1;

two->value = 2;
public:
three->value = 3;
int value;

Node* next;
// Connect nodes

}; one->next = two;

two->next = three;

Data Structures & Algorithms Lecture 4: Linked Lists three->next = NULL;


Simple Example

Do you see any problem in this code ???

Thursday, October 31, 2024


Example

Thursday, October 31, 2024


Linked List Example (Simple)

#include <iostream> void display() {

struct Node* ptr;

using namespace std; ptr = head;

while (ptr != NULL) {

struct Node { cout<< ptr->data <<" ";

int data; ptr = ptr->next;

struct Node *next; }

}; }

int main() {

struct Node* head = NULL; insert(3);

insert(1);

void insert(int new_data) {


Data Structures & Algorithms Lecture 4: Linked Lists insert(7);
Declarations Singly linked
list
•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:

struct ListNode

float value;

struct ListNode *next;

};
Data Structures & Algorithms Lecture 4: Linked Lists
Declaration
s
•The next step is to declare a pointer to serve as the list
head, as shown below.

ListNode *head;

•Once you have declared a node data structure and have


created a NULL head pointer, you have an empty linked

list.
Data Structures & Algorithms Lecture 4: Linked Lists
Program 1

list.appendNode(2.5);

list.appendNode(7.9);

list.appendNode(12.6);

Thursday, October 31, 2024


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 isLecture


Data Structures & Algorithmsassigned
4: Linked Lists to the node's next
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.

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 Lecture


Data Structures & Algorithms
last 4:node. Add the new node to the end
Linked Lists
Linked List Example
//floatList.h
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 displayList(void);
void deleteNode(float);
};
Data Structures & Algorithms Lecture 4: Linked Lists
Linked List Example
//floatList.h
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 displayList(void);
void deleteNode(float);
};
Data Structures & Algorithms Lecture 4: Linked Lists
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 pseudo code is shown below:

► 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.

Data Structures & Algorithms Lecture 4: Linked Lists


Appending a node to the list
void FloatList::appendNode(float num)
void main (void)
{
{
ListNode *newNode, *nodePtr;
FloatList list;
list.appendNode(2.5);
// Allocate a new node & store num
list.appendNode(7.9);
newNode = new ListNode;
list.appendNode(12.6);
newNode->value = num;
}
newNode->next = NULL;

// If there are no nodes in the list make newNode the first node
if (!head) // head == NULL
head = newNode;
else // Otherwise, insert newNode at end
{ nodePtr = head;
while (nodePtr->next) // Find the last node in the list
nodePtr = nodePtr->next;

nodePtr->next = newNode; // Insert newNode as the last node


}
}
Data Structures & Algorithms Lecture 4: Linked Lists
Appending a node to the list
void FloatList::appendNode(float num)
void main (void)
{
{
ListNode *newNode, *nodePtr;
FloatList list;
list.appendNode(2.5);
// Allocate a new node & store num
list.appendNode(7.9);
newNode = new ListNode;
list.appendNode(12.6);
newNode->value = num;
}
newNode->next = NULL;

// If there are no nodes in the list make newNode the first node
if (!head) // head == NULL
head = newNode;
else // Otherwise, insert newNode at end
{ nodePtr = head;
while (nodePtr->next) // Find the last node in the list
nodePtr = nodePtr->next;

nodePtr->next = newNode; // Insert newNode as the last node


}
}
Data Structures & Algorithms Lecture 4: Linked Lists
Appending a node to the list
void FloatList::appendNode(float num)
void main (void)
{
{
ListNode *newNode, *nodePtr;
FloatList list;
list.appendNode(2.5);
// Allocate a new node & store num
list.appendNode(7.9);
newNode = new ListNode;
list.appendNode(12.6);
newNode->value = num;
}
newNode->next = NULL;

// If there are no nodes in the list make newNode the first node
if (!head) // head == NULL
head = newNode;
else // Otherwise, insert newNode at end
{ nodePtr = head;
while (nodePtr->next) // Find the last node in the list
nodePtr = nodePtr->next;

nodePtr->next = newNode; // Insert newNode as the last node


}
}
Data Structures & Algorithms Lecture 4: Linked Lists
Appending a node to the list
void FloatList::appendNode(float num)
void main (void)
{
{
ListNode *newNode, *nodePtr;
FloatList list;
list.appendNode(2.5);
// Allocate a new node & store num
list.appendNode(7.9);
newNode = new ListNode;
list.appendNode(12.6);
newNode->value = num;
}
newNode->next = NULL;

// If there are no nodes in the list make newNode the first node
if (!head) // head == NULL
head = newNode;
else // Otherwise, insert newNode at end
{ nodePtr = head;
while (nodePtr->next) // Find the last node in the list
nodePtr = nodePtr->next;

nodePtr->next = newNode; // Insert newNode as the last node


}
}
Data Structures & Algorithms Lecture 4: Linked Lists
Appending a node to the list
void FloatList::appendNode(float num)
void main (void)
{
{
ListNode *newNode, *nodePtr;
FloatList list;
list.appendNode(2.5);
// Allocate a new node & store num
list.appendNode(7.9);
newNode = new ListNode;
list.appendNode(12.6);
newNode->value = num;
}
newNode->next = NULL;

// If there are no nodes in the list make newNode the first node
if (!head) // head == NULL
head = newNode;
else // Otherwise, insert newNode at end
{ nodePtr = head;
while (nodePtr->next) // Find the last node in the list
nodePtr = nodePtr->next;

nodePtr->next = newNode; // Insert newNode as the last node


}
}
Data Structures & Algorithms Lecture 4: Linked Lists
Appending a node to the list
void FloatList::appendNode(float num)
void main (void)
{
{
ListNode *newNode, *nodePtr;
FloatList list;
list.appendNode(2.5);
// Allocate a new node & store num
list.appendNode(7.9);
newNode = new ListNode;
list.appendNode(12.6);
newNode->value = num;
}
newNode->next = NULL;

// If there are no nodes in the list make newNode the first node
if (!head) // head == NULL
head = newNode;
else // Otherwise, insert newNode at end
{ nodePtr = head;
while (nodePtr->next) // Find the last node in the list
nodePtr = nodePtr->next;

nodePtr->next = newNode; // Insert newNode as the last node


}
}
Data Structures & Algorithms Lecture 4: Linked Lists
Appending a node to the list

Data Structures & Algorithms Lecture 4: Linked Lists


Appending a node to the list

Data Structures & Algorithms Lecture 4: Linked Lists


Appending a node to the list

Data Structures & Algorithms Lecture 4: Linked Lists


Program 2
// 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();
Data Structures & Algorithms Lecture 4: Linked Lists
Traversing the 27

List
• Algorithms that traverse a list start at the first node and examine each
node in succession until the last node has been processed
• Traversal logic is used by several different types of algorithms, such as
– changing a value in each node,
– printing the list,
– Performing an operation on a field in the list,
– or calculating the average of a field and etc…

• Any application that requires that the entire list be processed uses the
traversal

Data Structures & Algorithms Lecture 4: Linked Lists


Traversing the list

 To traverse the list we need a walking


(navigator/traversal) pointer
► This pointer is used to move from node to node as each
element is processed
► Example: displayList function….

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.

Data Structures & Algorithms Lecture 4: Linked Lists


Display list

void FloatList::displayList(void)
{
ListNode *nodePtr;
nodePtr = head;

while (nodePtr)
{
cout << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}

Data Structures & Algorithms Lecture 4: Linked Lists


Display list

void main(void)
{
FloatList List; OUTPUT
list.appendNode(2.5); 2.5
list.appendNode(7.9); 7.9
list.appendNode(12.6); 12.6
list.displayList();
}

Data Structures & Algorithms Lecture 4: Linked Lists


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


Data Structures & Algorithms Lecture 4: Linked Lists
Inserting a Node

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.


Data Structures & Algorithms Lecture 4: Linked Lists
The code for the traversal algorithm

(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;


Data Structures & Algorithms Lecture 4: Linked Lists
void FloatList::insertNode(float num)

ListNode *newNode, *nodePtr, *previousNode = NULL;

// 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) // if(head == NULL)

head = newNode;

newNode->next = NULL;

}
Thursday, October 31, 2024
Continued on next slide…
37

Continued from previous slide.

// If the new node is to be the 1st in the list,

// insert it before all other nodes. if (previousNode

== NULL)

head = newNode;

newNode->next = nodePtr;

else

previousNode->next = newNode; newNode->next =


Data Structures & Algorithms Lecture 4: Linked Lists
Program 3
// 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) Program Output


{ 2.5
FloatList list; 7.9

10.5
// Build the list list.appendNode(2.5);
12.6
list.appendNode(7.9); list.appendNode(12.6);

// Insert a node in the middle

// of &the
Data Structures list.
Algorithms Lecture 4: Linked Lists
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.

Thursday, October 31, 2024


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.

Thursday, October 31, 2024


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.

Thursday, October 31, 2024


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
Thursday, October 31, 2024
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

Data Structures & Algorithms Lecture 4: Linked Lists


Deleting a node

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;
}

Data Structures & Algorithms Lecture 4: Linked Lists


Deleting a node

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;
}
}

Data Structures & Algorithms Lecture 4: Linked Lists


Deleting a node

From: http://www.tutorialspoint.com/data_structures_algorithms/data_structures_algorithms_tutorial.pdf

Data Structures & Algorithms Lecture 4: Linked Lists


Program 4
// 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;


Continued on next slide…
cout << "Now
Data Structures deleting the node in the
& Algorithms Lecturemiddle.\n";
4: Linked Lists cout << "Here are the
48

Continued from previous slide.

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();
Data Structures & Algorithms Lecture 4: Linked Lists
}
49

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
Data Structures & Algorithms Lecture 4: Linked Lists
50

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.

Thursday, October 31, 2024


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.

Thursday, October 31, 2024


Destroying the List
52

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.

Data Structures & Algorithms Lecture 4: Linked Lists


53

FloatList::~FloatList(void)

ListNode *nodePtr, *nextNode;

nodePtr = head;

while (nodePtr != NULL)

nextNode = nodePtr->next; delete nodePtr;

nodePtr = nextNode;

}
Thursday, October 31, 2024
}

You might also like