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

03 Lists (Using Linked Lists)

Uploaded by

shane ocampo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

03 Lists (Using Linked Lists)

Uploaded by

shane ocampo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

LISTS

(USING LINKED LISTS)

SCHOOL OF COMPUTING MITCH M. ANDAYA


LINKED LIST IMPLEMENTATION OF LISTS

• A singly linked list, or simply linked list, consists of


ordered nodes wherein each node represents an item in
the list:

N1, N2, . . ., Nn

Each node is a structure with several fields (for the data of


each item in the list).

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

A linked list has a pointer (called start) that points to the


first node in the list (node N1). This allows the program to
easily locate the first node.

The last field of a node (referred to as the address field).

This will be a pointer that points to the next or succeeding


node in the list. This is how sequencing in a list is
achieved.

address field

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

In other words, the address field of Ni points to Ni+1. For


example, the address field of node N2 should point to node
N3.

The address field of the last node, Nn, contains a special


value called NULL which means that the address field of
the last node does not point to anything.

address field

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

Sample Definition of a Node:

struct NODE
{
char name[50];
char address[100];
int age;
float weight;
float height;
*
NODE *next;
};

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

• Example (List of Integers)

To simplify discussions, assume that the list is simply a list


of integers.

So the definition of a node is as follows:

struct NODE
{
int value;
NODE *next;
};

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

• Example (List of Integers):

Some important points:

1. This is an example of a linked list consisting of 4 nodes


representing a list of integers.

2. The pointer variable start contains the address of the first


node (start points to node 1) to indicate the first integer in the
list.

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

• Example (List of Integers):

3. Each node has two fields. The first field contains the value of
the integer.

4. The second field is the address field. As discussed earlier, the


address field of a particular node contains the address of the
node after it. In other words, the address field of a particular
node points to the next node in the list.

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

• Example (List of Integers):

5. The address field of the last node has the value NULL to
indicate that it is not pointing to any other node and that it is
the last node of the list.

6. This list represents the sequence: 111, 222, 333, 444

7. An empty list is a linked list that does not contain any node.
Since there is no first node, start is equal to NULL (start is not
pointing to anything).

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

• Sample Program to Create the Linked List of Integers:

#include <iostream>
using namespace std;

struct NODE
{
int value;
NODE *next;
};

Lists (Using Linked Lists)


LINKED LIST IMPLEMENTATION OF LISTS

main() 111 222 333 444


{
NODE node1, node2, node3, node4,*start;

node1.value = 111;
node2.value = 222; This program is not practical
node3.value = 333; since it is static (additional
node4.value = 444; nodes cannot be created while
the program is running).
start = &node1;
One of the advantages of
node1.next =&node2; linked lists is that programs can
node2.next =&node3; create additional nodes during
node3.next =&node4; run-time (to be discussed
node4.next = NULL; later).
}

Lists (Using Linked Lists)


THE malloc() FUNCTION

• When a program declares or defines a variable,


C++ will allocate main memory storage to that
variable and assigns a name to that storage.

• For example:

int x;

allocates four bytes of memory storage and the


name x is assigned or associated to that storage.

Lists (Using Linked Lists)


THE malloc() FUNCTION

• This kind of storage allocation is called compile-time


storage allocation since the system knows at compile time
the type and amount of storage required.

• It is also possible to allocate storage to variables when the


program is already running. This kind of storage allocation
is called run-time storage allocation.

• The malloc() function allocates an amount of storage


specified by the programmer and returns the address of
the storage allocated. If the function cannot find any
available storage in memory, it will return NULL.

Lists (Using Linked Lists)


THE malloc() FUNCTION

• To allocate one int cell, first define a pointer to an integer:

int *p;

then invoke the malloc() function

p = (int*) malloc(sizeof(int));

where the argument sizeof(int) is the number of bytes necessary


to store one int. Remember, sizeof() is a C++ function that returns
the number of bytes needed to store any data type.

malloc() returns a value which is the address of the storage


allocated and is stored into p.

Lists (Using Linked Lists)


THE malloc() FUNCTION

• Sample Program Using Run-time Allocation

#include <iostream>
#include <cstdlib>
using namespace std;

main()
{
int *p1;
char *p2;

p1 = (int*) malloc(sizeof(int));
p2 = (char*) malloc(sizeof(char));

Lists (Using Linked Lists)


THE malloc() FUNCTION

cout << "Enter an integer: ";


cin >>
*p1
;
cout << "Enter a character: ";
cin >> *p2;

cout << "\n\nThe integer you entered is " << *p1 << ".";
cout << "\n\nThe character you entered is " << *p2 << ".";
}

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

• Assume that there is already a linked list:

• To add a new node at the rear of the list, there must be a pointer
pointing to the last node of the list:

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

• To add a new node, first create a new node by executing:

ptr1 = (NODE*)
NODE malloc(sizeof(NODE));
NODE

This will create a new node and it will be pointed to by the


pointer ptr1.

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

555

• The next step is to put values in the fields of the new node.
To put data in the value field, execute:

ptr1 -> value = 555;

Or ask the user to input the data:

cout << "Enter the value of the node:";


cin >> ptr1 -> value;

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

555

• The next field should be made equal to NULL since the


new node will become the last node in the list.

This is done by executing:

ptr1 -> next = NULL;

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

• The next step is to attach the new node to the list.

This is done by making the next field of the last node in the
list (the one pointed to be ptr2) point to the newly
created node (the one pointed to by ptr1).

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

• To attach the node to the list, execute the following


statement:

ptr2 -> next = ptr1;

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

The last step is to make ptr2 point to the last node. The reason for
this is just in case another node will be added.

This is done by executing:

ptr2 = ptr2->next;

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

• Take note that if the newly created node happens to be the first node to be
created (the list is empty or start = NULL) , then make sure to make start and
ptr2 point to that node:

This is done by executing:

ptr1 = (NODE*) malloc(sizeof(NODE));


ptr1 -> value = 555;
ptr1 -> next = NULL;

if (start == NULL)
{
start = ptr1;
ptr2 = ptr1;
}

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

• Sample Program for Creating a Linked List (and then printing the nodes)

#include <iostream>
using namespace std;

struct NODE
{
int value;
NODE *next;
};

main()
{
NODE *start, *ptr1, *ptr2;
int i, number_of_nodes;

start = NULL;
cout << "Enter the number of nodes: ";
cin >> number_of_nodes;

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

for (i = 1; i <= number_of_nodes; ++i)


{
ptr1 = (NODE*) malloc(sizeof(NODE));
cout << "\nEnter the value of node " << i << ": ";
cin >> ptr1 -> value;
ptr1 -> next = NULL;

if (start == NULL)
{
start = ptr1;
ptr2 = ptr1;
}
else
{
ptr2 -> next = ptr1;
ptr2 = ptr2 -> next;
}
}

Lists (Using Linked Lists)


CREATING A LINKED LIST USING malloc()

if (start == NULL)
cout << "The list is empty!";
else
{
ptr1 = start;
i = 1;

while (ptr1 != NULL)


{
cout << "\nThe value of node " << i << " is " << ptr1 -> value <<".";
++i;
ptr1 = ptr1->next;
}
}
}

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• For the following programs for the operations on linked lists,


assume the following global definition:

struct NODE
{
int value;
NODE *next;
};

and the following local declaration in main():

NODE *start;

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• Take note that the linked list belongs to main().

start 111 222 333 444

• Since most functions for the operations on linked


lists need to access the list itself, it should be able to
access the pointer variable start.

• Therefore, it must be passed on to these functions as


an argument.

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• For example, the function list_empty() needs to access start to be able to


determine if the list is empty (by checking if start = NULL).

• In main (), this function can


be invoked by: local to main()

list_empty (start);

• The function must therefore be


defined as: local to the function

NODE *p
int list_empty (NODE *p) p

• It should be noted that list_empty() does not have to modify the value of
start.

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• Function to Check if List is Empty (returns 1 if empty and 0 if not


empty)

int list_empty (NODE *p)


{
if (p == NULL)
return (1);
else
return (0);
}

Take note that there is no need for a function to determine if a


linked list is full.

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• Function to Print the Contents of the List

void
void print_items (NODE
NODE *p)
{
int ctr;
p
if (list_empty(p) == 1)
cout << "\nThe List is Empty!";
else To invoke this function at main():
{
ctr = 1; print_items (start);
while (p != NULL)
{
cout << "\nThe value of node " << ctr << " is " << p -> value <<".";
p = p -> next;
++ctr;
}
}
}

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• Function to Count the Number of Items in a List (returns the count)

int count_items (NODE


NODE *p)
{
int ctr;
p
ctr = 0;
while (p != NULL)
{
++ctr; To invoke this function at main():
p = p -> next;
count = count_items (start);
}
return (ctr);
}

Lists (Using Linked Lists)


SOME OPERATIONS ON LINKED LISTS

• Function to Locate an Item in a List and Print its Position (assuming items are unique)

void locate_item (NODE


void NODE *p,
*p, int
int search_data)
search_data)
{
int ctr;

if (list_empty(p) == 1)
cout << "\nThe List is Empty!";
else p
{
ctr = 1;
while (p p != NULL && p -> value != search_data
search_data)
{
p = p -> next;
++ctr; To invoke this function at main():
}
if (p NULL)
p != NULL
locate_item (start, key);
cout << "Node requested is Node " << ctr << ".";
else
cout << "Node Does Not Exist.";
}
}

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• Assume the node will be inserted at position pos. The first step is
to create a new node and enter the necessary values (assume the
pointer ptr will point to the new node and the variable new_data
contains the value of this node):

ptr = (NODE*) malloc(sizeof(NODE));


ptr -> value = new_data;

start 111 222 333 444

999

ptr

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• If pos = 1 (the new node will become the first node in the list):

start 111 222 333 444

999

ptr

This is accomplished by the following code:

ptr -> next = start;


start = ptr;

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• If pos > 1, then the next step is to have two pointers (before and here) to point
to the nodes before and at the position where the node is to be inserted.

In other words, before should point to the node at position pos – 1 and here
should point to the node at position pos.

Assume pos = 3

• To insert the node (pointed to


by ptr) in the list, execute:

before -> next = ptr;


ptr -> next = here;

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• To move the pointers before and here to their respective positions (the pointer
before at pos -1 and the pointer here at pos):
2 3 4 5 6 7 8

before = start;
here = start -> next;
Once before and here
are in their respective ctr = 1;
starting positions, they while (ctr <= pos-2)
would have to be
moved pos – 2 times. {
before = before -> next;
here = here -> next;
++ctr;
}

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• So to insert a new node within the list, the following program segment must
be executed:
else
{
before = start;
ptr = (NODE*) malloc(sizeof(NODE)); here = start -> next;
ptr -> value = new_data; ctr = 1;
while (ctr <= pos-2)
if (pos == 1) {
{ before = before -> next;
ptr -> next = start; here = here -> next;
start = ptr; ++ctr;
} }
before -> next = ptr;
ptr -> next = here;
}

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• Take note that if pos = 1 (or if the list is empty), the insert
function should make the pointer start point to the newly
created node.

if (pos == 1)
{
ptr -> next = start;
start = ptr;
}

• This would mean that the function to insert a node would have
to modify the value of start which is a local variable to main() or
to some other function.

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• For the insert_node() function to do this, the address of start


(which is a pointer) must be passed on to the function.

• In main (), the insert_node() function can be invoked by:

insert_node (&start, …);

• Consequently, the function must have a pointer to start to store


this address (a pointer to another pointer):

void insert_node ( NODE


NODE***ptr_start, …)

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• So the insert function will have a pointer to the pointer start.


To make start point to the newly created node:

if (pos == 1) start 111 222 333 444

{
ptr -> next = start;
*ptr_start; 999
start
*ptr_start
= ptr;= ptr; ptr_start
ptr
}

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• Function to Insert a Node Within a Linked List

void insert_node (NODE


NODE **ptr_start, int new_data,
new_data, int int pos)
pos)
{
NODE *ptr, *before,
*before, *here;
*here; To invoke this function at main():
int ctr;
insert_node (&start, add_data, position);

ptr = (NODE*) malloc(sizeof(NODE));


ptr -> value = new_data;

if (pos == 1)
{
ptr -> next = *ptr_start;
*ptr_start = ptr;
}

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

else
{
*ptr_start;
before = start;
(*ptr_start)
here = start -> next;-> next;
ctr = 1;
while (ctr <= pos-2) ptr_start
{
before = before -> next;
here = here -> next;
++ctr;
}
before -> next = ptr;
ptr -> next = here;
}
cout << "\nItem Successfully Added!";
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• Assume that the value of the node to be deleted is stored in a


variable called delete_value.

• There should be a pointer (discard) to point to the node to be


deleted and another pointer (before) to point to the node before
the node to be deleted.

• Assuming that delete_value = 333:

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

To make discard point to the node to be deleted (and before point to the
preceding node):

discard = start;
while (discard
discard != NULL && discard -> value != delete_value
delete_value)
{
before = discard;
discard = discard->next;
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• To remove the node (pointed to by discard) from the list, execute:

before -> next = discard -> next;

The node containing 333


is no longer part of the list
(it has been "deleted"
from the list).

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• So to delete a node in the list, the following program segment


must be executed:

discard = start;

while (discard != NULL && discard -> value != delete_value)


{
before = discard;
discard = discard->next;
}

before -> next = discard -> next;

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST
• Take note that after the while (discard != NULL && discard->value !=
delete_value) loop finishes executing and discard = NULL; this means the
node to be deleted does not exist. So the program segment to delete a
node must be revised as follows:

discard = start;

while (discard != NULL && discard -> value != delete_value)


{
before = discard;
discard = discard->next;
}

if (discard == NULL)
cout << "\nNode To Be Deleted Does Not Exist!";
else
before -> next=discard -> next;

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• If the node to be deleted happens to be the first node in the list, start
should now point to the second node and delete the designated node.

So the program segment to delete a node will now be:

discard = start;

If (start -> value == delete_value)


start = start -> next;

start 111 222

discard

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

else
{
while (discard != NULL && discard -> value != delete_value)
{
before = discard;
discard = discard->next;
}
if (discard == NULL)
cout << "\nNode To Be Deleted Does Not Exist!";
else
before -> next = discard -> next;
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• Deleting a node from a linked list actually means removing it from


the list.

• Although the node containing 333 is no longer part of the linked


list, it has not been destroyed. Unless the program explicitly
eliminates the node, it will remain in storage and will waste
precious memory space.

• C++ has a built-in function that eliminates dynamic variables to


free some storage for other purposes. This function is known as
free().

• To free up the memory space occupied by the node pointed to by


discard, execute free(discard). Note that the pointer discard still
exists, only the node pointed to by it was destroyed.

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• So to delete a node in the list and then destroying the deleted


node, the following program segment must be executed:

discard = start;

If (start -> value == delete_value)


{
start = start -> next;
free (discard);
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

else
{
while (discard != NULL && discard -> value != delete_value)
{
before = discard;
discard = discard->next;
}
if (discard == NULL)
cout << "\nNode To Be Deleted Does Not Exist!";
else
{
before -> next = discard -> next;
free(discard);
}
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• Function to Delete a Node in a Linked List

void delete_node (NODE **ptr_start, int delete_value)


{
To invoke this function at main():
NODE *discard, *before;

discard = *ptr_start; delete_node (&start, delete_data);

if (list_empty(*ptr_start) == 1)
cout << "\nThe List is Empty!";
else
{
if ((*ptr_start) -> value == delete_value)
{
*ptr_start = (*ptr_start) -> next;
free(discard);
cout << "\nItem Successfully Deleted!";
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

else
{
while (discard != NULL && discard -> value != delete_value)
{
before = discard;
discard = discard -> next;
}
if (discard == NULL)
cout << "\nNode To Be Deleted Does Not Exist!";
else
{
before -> next = discard -> next;
free(discard);
cout << "\nItem Successfully Deleted!";
}
}
}
}

Lists (Using Linked Lists)


LINKED LISTS VERSUS ARRAYS

• Advantages of Using Linked Lists in Implementing


Lists:

– Faster/Easier in inserting/deleting nodes.


Unlike in arrays wherein several elements have
to be moved every time a single element is
inserted or deleted in the array.

– Dynamic size. Theoretically, using linked lists


does not put any limit on the number of items
the list can have. The only limitation is the size
of the physical memory of the machine.
Lists (Using Arrays)
LINKED LISTS VERSUS ARRAYS

• Disadvantages of Using Linked Lists in


Implementing Lists:

– More memory space is needed. As mentioned


before, an array of 1,000 char elements
requires only 1,000 bytes. While a linked list of
1,000 char elements requires 16,000 bytes.

– Direct access to a node is not allowed. The


program has to access nodes sequentially
starting from the first node.

Lists (Using Arrays)


DOUBLY LINKED LISTS

• Disadvantages of singly linked lists:

1. A program cannot traverse such a list backwards.

2. A program cannot delete a node from the list given only a


pointer to that node (there is a need for the before pointer).

• In a doubly linked list, each node contains two pointers. One


pointer points to the node’s predecessor while the other points to
its successor.

Lists (Using Linked Lists)


DOUBLY LINKED LISTS

• Sample declaration:

struct NODE
{
int data;
NODE *prev;
NODE *next;
};

The prev field points to the previous node in the list while
the next field points to the next node in the list.

Lists (Using Linked Lists)


DOUBLY LINKED LISTS

• Deleting a Node

Assume that a pointer discard points to the node to be deleted.

Algorithm to delete a node pointed to by discard:

discard -> next -> prev = discard -> prev;


discard -> prev-next = discard -> next;
free (discard);

Lists (Using Linked Lists)


DOUBLY LINKED LISTS

• Function to Delete a Node in a Doubly Linked List

void delete_node (NODE **ptr_start, int delete_value)


{
NODE *discard, *before;

discard = *ptr_start;

if ((*ptr_start) -> value == delete_value)


{
*ptr_start = (*ptr_start) -> next;
(*ptr_start) -> prev = NULL;
free(discard);
}

Lists (Using Linked Lists)


DOUBLY LINKED LISTS

else
{
while (discard != NULL && discard -> value != delete_value)
discard = discard -> next;

if (discard == NULL)
cout << "\nNode to be deleted does not exist!";
else
{
discard -> next -> prev = discard -> prev;
discard -> prev -> next = discard -> next;
free(discard);
}
}
}

Lists (Using Linked Lists)


DOUBLY LINKED LISTS

• Inserting a Node

Assume that a pointer before points to the node that precedes the node to be inserted and
that pointer new points to the node to be inserted.

Algorithm to insert a node pointed:

ptr -> next = before -> next;


ptr -> prev = before;
before -> next-> prev = ptr;
before -> next = ptr;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Traversing a linked list means visiting each and every node in the
list and perhaps performing a necessary operation (such as
printing or displaying the contents of the node).

To traverse a linked list, it is necessary to use a pointer (not start)


and use it to point at each node in the list one at a time.

Always remember that the pointer start should not be moved (it
should always point to the first item in the list).

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

First, let there be another NODE pointer called ptr.

The pointer ptr should point to the first node (ptr should point to
the same thing start is pointing at). This is done by executing:

ptr = start;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

First, let the pointer ptr point to the first node (ptr should point to
the same thing start is pointing at). This is done by executing:

ptr = start;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

First, let there be another NODE pointer called ptr.

The pointer ptr should point to the first node (ptr should point to
the same thing start is pointing at). This is done by executing:

ptr = start;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

First, let the pointer ptr point to the first node (ptr should point to
the same thing start is pointing at). This is done by executing:

ptr = start;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

To print the data of that node, execute:

cout << "The value of the node is " << (*ptr).value << ".";

or it may be written as:

cout << "The value of the node is " << ptr -> value << ".";

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Then let the pointer ptr point to the second node in the list. This
is done by executing:

ptr = ptr -> next;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

To print the data of that node, execute again:

cout << "The value of the node is " << ptr -> value << ".";

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Then let the pointer ptr point to the third node in the list. This is
done by executing:

ptr = ptr -> next;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

To print the data of that node, execute again:

cout << "The value of the node is " << ptr -> value << ".";

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Then let the pointer ptr point to the fourth node in the list. This is
done by executing:

ptr = ptr -> next;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

To print the data of that node, execute again:

cout << "The value of the node is " << ptr -> value << ".";

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Summary of the algorithm for traversing the list:

1. Let ptr point to the first node.

2. Repeat the following:

cout << "\nThe value …


ptr = ptr -> next;

until the last node is visited (printed).

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Take note that if the pointer ptr is pointing to the last node
and the instruction ptr = ptr -> next; is executed, ptr will
become equal to NULL. This means that there are no more
nodes to be traversed so the loop should be terminated.

So while ptr is not equal to NULL, the loop should


continue.

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

Program segment for traversing the list:

ptr = start;

while (ptr != NULL)


{
cout << "The value of the node is " <<
ptr -> value << ".";
ptr = ptr -> next;
}

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

• Sample Program to Create the Linked List of Integers (with


printing of nodes):

#include <iostream>
using namespace std;

struct NODE
{
int value;
NODE *next;
};

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

main()
{

NODE node1, node2, node3, node4, *start;


int ctr;

node1.value = 111;
node2.value = 222;
node3.value = 333;
node4.value = 444;

start = &node1;
node1.next =&node2;
node2.next =&node3;
node3.next =&node4;
node4.next = NULL;

Lists (Using Linked Lists)


TRAVERSING A LINKED LIST

ptr = start;
ctr = 1;

while (ptr != NULL)


{
cout << "\nValue of node " << ctr << " is "
<< ptr -> value <<".";
++ctr;
ptr = ptr->next;
}
}

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• If pos = 1 (the new node will become the first node in the list):

start 111 222 333 444

999

ptr

This is accomplished by the following code:

ptr -> next = start;


start = ptr;

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• Assume the node will be inserted at position pos. The first step is to create a
new node and enter the necessary values (assume the pointer ptr will point to
the new node and the variable new_data contains the value of this node):

ptr = (NODE*) malloc(sizeof(NODE));


ptr -> value = new_data;
ptr -> next = NULL;

start 111 222 333 444

999

ptr

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• If pos > 1, then the next step is to have two pointers (before and here) to point
to the nodes before and at the position where the node is to be inserted.

In other words, before should point to the node at position pos – 1 and here
should point to the node at position pos.

Assume pos = 3

• To insert the node (pointed to


by ptr) in the list, execute:

before -> next = ptr;


ptr -> next = here;

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

• If pos > 1, then the next step is to have two pointers (before and here) to point
to the nodes before and at the position where the node is to be inserted.

In other words, before should point to the node at position pos – 1 and here
should point to the node at position pos.

Assume pos = 3

• To insert the node (pointed to


by ptr) in the list, execute:

before -> next = ptr;


ptr -> next = here;

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• Assume that there is already a linked list:

• The first step is to create a new node and enter the necessary
values (assume the pointer ptr1 will point to the new node and
the variable new_data contains the value of this node):

ptr1 = (NODE*) malloc(sizeof(NODE));


ptr1 -> value = new_data;
ptr1 -> next = NULL;

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• Next is to have a pointer (ptr2) point to the last element in the list.

This is done by executing:

ptr2 = start;
while (ptr2 -> next != NULL)
ptr2 = ptr2 -> next;

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• The last step is to attach the new node to the list:

This is done by executing:

ptr2 -> next = ptr1;

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• So to add a new node at the rear of the list, the


following program segment must be executed:

ptr1 = (NODE*) malloc(sizeof(NODE));


ptr1 -> value = new_data;
ptr1 -> next = NULL;

ptr2 = start;
while (ptr2 -> next != NULL)
ptr2 = ptr2 -> next;
ptr2 -> next = ptr1;

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• If the list happens to be empty (start = NULL), then the program should
ensure that the pointer start should point to the newly created node. So
the program segment to add the new node will now be:

ptr1 = (NODE*) malloc(sizeof(NODE));


ptr1 -> value = new_data;
ptr1 -> next = NULL;
if (list_empty (start) == 1)
start = ptr1;
else
{
ptr2 = start;
while (ptr2 -> next != NULL)
ptr2 = ptr2 -> next;
ptr2 -> next = ptr1;
}

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• This would mean that the function to add a node would have to
modify the value of start which is a local variable to main() or to
some other function.

• For the add_item() function to do this, the address of start


must be passed on to the function. Consequently, the function
must have a pointer to start to store this address (a pointer to
another pointer):

void add_item ( …., NODE **ptr_start, …)

• In main (), the add_item() function can be invoked by:

add_item ( …., &start, …);

Lists (Using Linked Lists)


ADDING A NODE IN A LINKED LIST (AT THE REAR)

• Function to Add a Node in a Linked List (at the rear)

void add_item (NODE **ptr_start, int new_data)


{
NODE *ptr1, *ptr2;

ptr1 = (NODE*) malloc(sizeof(NODE));


ptr1 -> value = new_data; To invoke this function at main():
ptr1 -> next = NULL;
add_item (&start, add_data);
if (list_empty (*ptr_start) == 1)
*ptr_start = ptr1;
else
{
ptr2 = *ptr_start;
while (ptr2 -> next != NULL)
ptr2 = ptr2 -> next;
ptr2 -> next = ptr1;
}
}

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• Assume that the value of the node to be deleted is stored in a


variable called delete_value.

• There should be a pointer (discard) to point to the node to be


deleted and another pointer (before) to point to the node before
the node to be deleted.

• Assuming that delete_value = 333:

Lists (Using Linked Lists)


INSERTING A NODE WITHIN A LINKED LIST

start 111 222 333 444

before here

999

ptr

• To insert the node (pointed to by ptr) in the list, execute:

before -> next = ptr;


ptr -> next = here;

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• To remove the node (pointed to by discard) from the list, execute:

before -> next = discard -> next;

The node containing 333


is no longer part of the list
(it has been "deleted"
from the list).

Lists (Using Linked Lists)


DELETING A NODE IN A LINKED LIST

• To remove the node (pointed to by discard) from the list, execute:

before -> next = discard -> next;

The node containing 333


is no longer part of the list
(it has been "deleted"
from the list).

Lists (Using Linked Lists)

You might also like