100% found this document useful (1 vote)
59 views

Chapter 3 - CS

The document discusses linked lists including their advantages over arrays, how they are structured using nodes containing data and a pointer to the next node, and basic linked list operations like adding nodes to the start or end of the list and displaying the list.

Uploaded by

tasheebedane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
59 views

Chapter 3 - CS

The document discusses linked lists including their advantages over arrays, how they are structured using nodes containing data and a pointer to the next node, and basic linked list operations like adding nodes to the start or end of the list and displaying the list.

Uploaded by

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

1

Chapter 3
2

Linked Lists
Objective 3

At the end of the session students should have basic understanding of :

 Linked lists

 Basic operations of linked lists

 Insert, find, delete, print, etc.

 Types of linked lists

 Simple Linked Lists

 Doubly Linked Lists

 Circular Linked Lists


Array vs Linked List 4

Array node node

Linked List node


What’s wrong with Array ? 5

Even though arrays are simple and fast they have their own disadvantages.

Disadvantages of arrays as storage data structures

 slow searching in unordered array

 slow insertion in ordered array

 Fixed size
Why Linked lists?
 General purpose storage data structures and are versatile.
6
 More complex to code and manage than arrays, but they have some distinct
advantages.

 Dynamic: a linked list can easily grow and shrink in size.


 We don’t need to know how many nodes will be in the list. They are created in
memory as needed.

 In contrast, the size of a C++ array is fixed at compilation time.

 Easy and fast insertions and deletions


 To insert or delete an element in an array, we need to copy to temporary
variables to make room for new elements or close the gap caused by deleted
elements.

 With a linked list, no need to move other nodes. Only need to reset some
pointers.
Linked Lists 7
A B C 

Head

 A linked list is a series of connected nodes


 Each node contains at least
 A piece of data (any type)
 Pointer to the next node in the list
 Head: pointer to the first node
 The last node points to NULL

node
A
data pointer
Linked Lists 8

 Each data item is embedded in a link.

 Each Link object contains a reference to the next link in the list of items.

In an array

 items have a particular position, identified by its index.

In a list

 the only way to access an item is to traverse the list


Creating Linked Lists in C++ 9

A linked list is a data structure that is built from structures and pointers.

It forms a chain of "nodes" with pointers representing the links of the chain and
holding the entire thing together.
First, a little reminder on structure 10

Structures are defined using the struct keyword:

E.g. struct Time{


int hour;
int minute;
int second;
};

The struct keyword creates a new user defined data type that is used to declare
variables of an aggregate data type.
11

Structure variables are declared like variables of other types.

Syntax: struct <structure tag> <variable name>;


E.g. struct Time timeObject,
struct Time *timeptr;
Accessing Members of Structure Variables 12

The Dot operator (.): to access data members of structure variables.


The Arrow operator (->): to access data members of pointer variables pointing to
the structure.

E.g. Print member hour of timeObject and timeptr.


cout<< timeObject.hour; or
cout<<timeptr->hour;

TIP: timeptr->hour is the same as (*timeptr).hour.


Self-Referential Structures 13

Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.
Defining the data structure for a linked list 14

The key part of a linked list is a structure, which holds the data for each node, and, most
importantly, a pointer to the next node.

E.g. struct node


{
char name[20]; // Name up to 20 letters
int age;
float height; // in metres
node *nxt;// Pointer to next node
};
struct node *start_ptr = NULL;
Adding a node to the list 15

we will assume that the node has to be added to the end of the list, although it
could be added anywhere in the list (a problem we will deal with later on).

Firstly, space for a pointer item is declared and assigned to a temporary pointer.

node *temp;
temp = new node;
16

Having declared the node, we ask the user to fill in the details of the person, i.e.
the name, age, address or whatever:

cout << "Please enter the name of the person: ";


cin >> temp->name;
cout << "Please enter the age of the person : ";
cin >> temp->age;
cout << "Please enter the height of the person : ";
cin >> temp->height;
temp->nxt = NULL;
17

Having set up the information, we have to decide what to do with the pointers. If
the list is empty to start with, there's no problem - just set the Start pointer to point
to this node.

if (start_ptr == NULL)
start_ptr = temp;
18

It is harder if there are already nodes in the list. In this case, the secret is to declare
a second pointer, temp2, to step through the list until it finds the last node.

temp2 = start_ptr;
// We know this is not NULL - list not empty!
while (temp2->nxt != NULL)
{ temp2 = temp2->nxt; // Move to next link in chain
}
+ 19

temp2->nxt = temp;
The full code 20

void add_node_at_end () // Set up link to this node


{ node *temp, *temp2; // Temporary pointers if (start_ptr == NULL)
// Reserve space for new node and fill it with start_ptr = temp;
data Else
temp = new node; { temp2 = start_ptr;
cout << "Please enter the name of the person: // We know this is not NULL - list not empty!
";
while (temp2->nxt != NULL)
cin >> temp->name;
{ temp2 = temp2->nxt;
cout << "Please enter the age of the person : ";
// Move to next link in chain
cin >> temp->age; }
cout << "Please enter the height of the temp2->nxt = temp;
person : ";
}
cin >> temp->height;
}
temp->nxt = NULL;
Add a node at the start 21

 void add_node_at_start ( )  if (start_ptr == NULL) {


 {  start_ptr = temp;
 node *temp; // Temporary pointers  temp->nxt = NULL;}
 // Reserve space for new node and fill it with
 else
data
 temp = new node;  {
 cout << "Please enter the name of the person: ";  temp->nxt = start_ptr;
 cin >> temp->name;  start_ptr=temp;
 cout << "Please enter the age of the person : ";  }
 cin >> temp->age;
 }
 cout << "Please enter the height of the person :
";
 cin >> temp->height;
Displaying the list of nodes 22

Steps
1. Set a temporary pointer to point to the same thing as the start pointer.
2. If the pointer points to NULL, display the message "End of list" and stop.
3. Otherwise, display the details of the node pointed to by the start pointer.
4. Make the temporary pointer point to the same thing as the nxt pointer of the node it
is currently indicating.
5. Jump back to step 2.
Displaying the list of nodes 23

void display(){ temp = temp->nxt;


node *temp;
}
temp = start_ptr;
} while (temp != NULL);
do
{ if (temp == NULL) }
cout << "End of list" << endl;
else
{ // Display details for what temp points to
cout << "Name : " << temp->name << endl;
cout << "Age : " << temp->age << endl;
cout << "Height : " << temp->height << endl;
cout << endl; // Blank line
// Move to next node (if present)
Navigating through the list 24

Navigating is necessary when you want to insert or delete a node from somewhere
inside the list, as you will need to specify the position.

Navigation through the list is done with a pointer that moves backwards and
forwards through the list.
25

 First of all, a mobile pointer current is declared, and set to the same value as the
start_ptr pointer:

node *current;
current = start_ptr;

It's easy to get the current pointer to point to the next node in the list
current = current->nxt;
26

It is better to check that current isn't pointing to the last item in the list. If it is,
then there is no next node to move to:

if (current->nxt == NULL)
cout << "You are at the end of the list." << endl;
else
current = current->nxt;
27

Moving the current pointer back one step is a little harder. This is because we
have no way of moving back a step automatically from the current node.

The only way to find the node before the current one is to start at the beginning,
work your way through and stop when the node before the one considered is
found.
28

if (current == start_ptr)
cout << "You are at the start of the list" << endl;
else
{ node *previous; // Declare the pointer
previous = start_ptr;
while (previous->nxt != current)
{ previous = previous->nxt;
}
current = previous;
}
Add a node at a specific position 29

void add_position(int pos) cout << "Please enter the name of the person:
";
{
if(start_ptr!=NULL){ cin >> temp->name;

node *pre; cout << "Please enter the age of the person :
";
node *cur;
cin >> temp->age;
node *temp=new node;
cout << "Please enter the height of the
cur=start_ptr; person : ";
for(int i=1;i<pos;i++) cin >> temp->height;
{ pre->nxt=temp;
pre=cur; temp->nxt=cur;
cur=cur->nxt; }
} }
Deleting a node from the list 30

A node can be deleted from the start of the list, from the end of the list, or from
somewhere in the middle.

When a node is deleted, the space that it took up should be reclaimed. Otherwise
the computer will eventually run out of memory space. This is done with the
delete instruction:

delete temp; // Release the memory pointed to by temp


Delete a node from the start 31

void delete_start_node()
{ node *temp;
we can't just delete the nodes as it would temp = start_ptr;

break the chain. We need to reassign the if (temp!= NULL){


start_ptr = start_ptr->nxt;
pointers and then delete the node at the last
delete temp;
moment. }
else
{
cout<<"No item to delete\n";
}
}
Example 32
head

6 4 17 42

head

6 4 17 42

head

4 17 42
Delete a node from the end 33

Deleting a node from the end of the list is harder, as the temporary pointer must
find where the end of the list is by jumping along from the start.

It is necessary to maintain two temporary pointers, temp1 and temp2. The pointer
temp1 will point to the last node in the list and temp2 will point to previous to the
last node.
Steps 34
1. Look at the start pointer. If it is NULL, then the list is empty, so print out a "No
nodes to delete" message.
2. Make temp1 point to whatever the start pointer is pointing to.
3. If the nxt pointer of what temp1 indicates is NULL, then we've found the last node
of the list, so jump to step 7.
4. Make another pointer, temp2, point to the current node in the list.
5. Make temp1 point to the next item in the list.
6. Go to step 3.
7. If you get this far, then the temporary pointer, temp1, should point to the last item
in the list and the other temporary pointer, temp2, should point to the last-but-one
item.
8. Delete the node pointed to by temp1.
9. Mark the nxt pointer of the node pointed to by temp2 as NULL - it is the new last
node.
35
36
Deletion Description 37

head

6 4 17 42
head

6 4 17 42

head

6 4 17
38

void delete_end_node() else{


{ while(temp1->nxt!=NULL)
node *temp1; {
node *temp2;
temp2=temp1;
temp1=start_ptr;
temp1=temp1->nxt;
if (temp1== NULL)
}
cout<<"No item to delete\n";
delete temp1;
else if (temp1->nxt== NULL)
{ temp2->nxt=NULL;
start_ptr=NULL; }
delete temp1; }
}
Linked List Efficiency 39

 Insertion and deletion at the beginning of the list are very fast, O(1).

 Finding, deleting or inserting in the list requires searching through half the items
in the list on an average, requiring O(n) comparisons.

 Although arrays require same number of comparisons, the advantage lies in the
fact that no items need to be moved after insertion or deletion.

 As opposed to fixed size of arrays, linked lists use exactly as much memory as is
needed and can expand.
40

Doubly Linked Lists


41

A doubly linked list is one where there are links from each node in both
directions.

Each node in the list has two pointers, one to the next node and one to the
previous one - again, the ends of the list are defined by NULL pointers.
42

There is no pointer at the start of the list. Instead, there is simply a pointer to some
position in the list that can be moved left or right.

The reason a start pointer is needed in ordinary linked list is because, having
moved on from one node to another, we can't easily move back, so without the
start pointer, we would lose track of all the nodes in the list that we have already
passed.
Creating Doubly Linked Lists 43

The nodes for a doubly linked list would be defined as follows:

struct node{
char name[20];
node *nxt; // Pointer to next node
node *prv; // Pointer to previous node
};
node *current;

current = new node;


current->name = "Fred";
current->nxt = NULL;
current->prv = NULL;
Adding a Node at the start of a Doubly 44

Linked List
struct node{ void add_node_at_start () {

char name[20]; node *temp = new node;

node *nxt; // Pointer to next node cout<<"\n Enter your Name\n";

node *prv; // Pointer to previous node cin>> temp->data;

}; temp->prev = NULL;

struct node *current=NULL; temp->next = current;


if(current != NULL) {
current>prev = temp; }
current= temp;
}
Adding a Node at the end of a Doubly 45
Linked List
void add_node_at_end ()
{ node *temp, *temp2;
temp = current;
while (temp->nxt != NULL) {
temp = temp->nxt;}
temp2 = new node;
temp2->name = new_name; // Store the new name in the node
temp2->nxt = NULL; // This is the new start of the list
temp2->prv = temp; // Links to current list
temp->nxt = temp2;
}
46
Deleting a node from doubly linked list

Write a code to delete a node from a doubly linked list


(anywhere) in your peer group.
47
Reading Assignment

Circular linked list


48

The End

You might also like