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

Chapter 3 - Linked Lists

This document provides an overview of linked lists, including singly linked lists, doubly linked lists, and circular lists, along with their definitions and operations. It explains data structures at three levels: application, logical, and implementation, and details how to create, access, and manipulate linked lists in C++. Additionally, it covers operations such as adding, deleting, and traversing nodes within linked lists.
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
0% found this document useful (0 votes)
2 views

Chapter 3 - Linked Lists

This document provides an overview of linked lists, including singly linked lists, doubly linked lists, and circular lists, along with their definitions and operations. It explains data structures at three levels: application, logical, and implementation, and details how to create, access, and manipulate linked lists in C++. Additionally, it covers operations such as adding, deleting, and traversing nodes within linked lists.
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/ 50

Data Structures and

Algorithms
Linked
Lists
Linked Lists
This chapter covers:
Singly linked lists
Doubly linked lists
Circular lists

2
Data Structure and
Applications
In computer Science data can be seen from
three different levels:
I) Application (user) level – is a level which
models real life data in a specific context.
 It answers the question “why data is needed to be
modelled?”
 e.g. HU Library, HU students

3

ii) Logical or abstract data type level – indicates
the abstract view of the domain and
operations.
 It specifies the type of data stored and the operations
supported on them.
 This allows the user to create data types to their own
specifications.
 The purpose of the abstract data type is to answer
the question “what data is to be stored?” and “what
operations are made on the data?”
 Example: data to be stored ( domain of application)
– collection books
 valid operations on this domain
searching books
Sorting collection of book by title, author,…
Inserting (adding) new books
Reserving books
Selling a book (not valid operation)
Selling a car ( not valid operation)
4

iii) Implementation (Data structure) level – is a
specific representation of the data structure to
hold the data items and the coding for operations.
 It answers “how is data represented?”.
 Example:
a) int BookId[1000]; b) struct
HULibBook
bool BooksRes[1000]; {
char BookTitle[1000][15]; int BookId;
bool
BookRes;
char
BookTitle[15];
};
HULibBook
Book[1000];
c) struct HULibBook
{
int BookId;
bool BookRes;
char BookTitle[15]; 5
HULibBook *Next;
Structures
Structures are aggregate data types built using elements of primitive
data types.
Structure 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.
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
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;
3.1.2. Self-Referential Structures
Structures can hold pointers to instances of themselves. Or those
structure in which one or more pointers point to the structure of the
same type.
struct list{
char name[10];
int count;
struct list *next;
}; //this is single self-referential
However, structures cannot contain instances of themselves.
Because, his will result in infinite recursive call to the
Creating Linked Lists in C++
A linked list is a data structure which 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.
Graphically,

8
..
This linked list has four nodes in it, each
with a link to the next node in the series.

The last node has a link to the special value


NULL, which any pointer (whatever its type)
can point to, to show that it is the last link in
the chain.

There is also another special pointer, called


Head or Start, which points to the first link
in the chain so that we can keep track of it.

9
Array Vs Linked List

Array Linked List


Fixed Size Dynamic Size

Insertion and Deletion of Insertion and Deletion of element


element is expensive is simple

Elements store in Elements are not store in


sequentially one after the continues manner. Accessed by
other pointers

Random access possible Random access not allowed

No extra space Extra memory space required to


store pointers for each node
Definition and Operations
on Data Structures
i) Definition of Data Structures
A) Array Structure:
struct Node
{
char name[15];
int age;
float height;
};
Node person[1000];

11
...

B) Single Linked List


struct node {
char name[20]; // Name of up to 20
chars
int age; // BirthDate would be
better
float height; // In meters
node *nxt; // Pointer to next node
};
node *start_ptr = NULL;
//start_ptr will permanently point 12 to the

The key part of a linked list is a structure,
which holds the data for each node (the
name, address, age or whatever for the
items in the list), and, most importantly, a
pointer to the next node.

The important part of the above structure


is the line before the closing curly
brackets.

This gives a pointer to the next node in the


list.

This is the only case in C++ where


13 you are
ii) Storing and accessing
Data files
Array:
person[0].name = “Abebe”
person[0].age = 20;
person[0].height = 1.6

Single Linked List


Firstly, we declare the space for a pointer item and
assign a temporary pointer to it. This is done using
the new statement as follows:
temp = new node;

14

Then we will fill details of the person
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;

15
The last line sets the pointer from this

If the list is empty to start with, there's no problem - just
set the Start pointer to point to this node (i.e. set it to the
same value as temp):
if (start_ptr == NULL)
start_ptr = temp;
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;
while (temp2->nxt != NULL)
{
temp2 = temp2->nxt;
}
Then,
temp2->nxt = temp;

Graphically

17
iv) Traversing (Displaying the list
of nodes)
Array:
for (i=0;i<=lastperson;i++)
{
cout<<”Person Name:” <<person[i].
name;
cout<<”Book
Reserved :”<<person[i].age;
cout<<”Book Borrowed :”<< person[i].
height;
}

18

Single Linked List:
Having added one or more nodes, we
need to display the list of nodes on the
screen.
This is comparatively easy to do. Here is
the method:
Set a temporary pointer to point to the same
thing as the start pointer.
If the pointer points to NULL, display the
message "End of list" and stop.
Otherwise, display the details of the node
pointed to by the start pointer.
Make the temporary pointer point to the
same thing as the nxt pointer of the node it
is currently indicating.
Jump back to step 2. 19

temp = start_ptr;
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)
temp = temp->nxt; 20
}
v) Deleting a node from the list
When it comes to deleting nodes, we
have three choices:
Delete a node from the start of the list,
delete one from the end of the list, or
delete one 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
21

However, we can't just delete the nodes willy-
nilly as it would break the chain.
We need to reassign the pointers and then
delete the node at the last moment.
Here is how we go about deleting the first
node in the linked list:
temp = start_ptr; // Make the temporary pointer
identical to the
// start pointer

22

Now that the first node has been safely
tagged (so that we can refer to it even when
the start pointer has been reassigned), we
can move the start pointer to the next node
in the chain:
start_ptr = start_ptr->nxt; // Second node in
chain.

23

.

24
Here is the function that deletes a
node from the start:
void delete_start_node()
{
node *temp;
temp = start_ptr;
start_ptr = start_ptr->nxt;
delete temp;
}

25
Deleting a node from the end
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 node26pointed to by
Suppose we want to delete the last
node from this list:

27
Let's get straight on with step2 - set the
pointer temp1 to the same as the start
pointer:

28
The nxt pointer from this node isn't NULL, so we
haven't found the end node. Instead, we set the
pointer temp2 to the same node as temp1

29
and then move temp1 to the next node in the list:

30
Going back to step 3, we see that temp1 still doesn't
point to the last node in the list, so we make temp2
point to what temp1 points to

31
and temp1 is made to point to the next node along:

32
Eventually, this goes on until temp1 really is pointing
to the last node in the list, with temp2 pointing to the
penultimate node:

33
Now we have reached step 8. The next thing to do is to
delete the node pointed to by temp1

34
and set the nxt pointer of what temp2 indicates to
NULL:

35
The code to delete last node.
void delete_end_node()
{
node *temp1, *temp2;
if (start_ptr == NULL)
cout << "The list is empty!" << endl;
else
{
temp1 = start_ptr;
if (temp1->nxt == NULL)
{ delete temp1;
start_ptr = NULL;
}
else
{
while (temp1->nxt != NULL)
{
temp2 = temp1;
temp1 = temp1->nxt;
}
delete temp1;
temp2->nxt = NULL;
}
}}

36
Navigating through the list

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

37
Deleting from the center of
the list
First navigate to the list (use above code)
if (current->nxt == NULL)
cout << "There is no node after current"
<< endl;
else
{
node *temp;
temp = current->nxt;
current->nxt = temp->nxt; // Could be
NULL
delete temp;
}
38
Here is the code to add a node
after the current one
if (current->nxt == NULL)
add_node_at_end();
else {
node *temp;
new temp;
get_details(temp);
//Make the new node point to the same
thing as the current node
temp->nxt = current->nxt;
//Make the current node point to the new link
in the chain
current->nxt = temp;
}
39
Add the node with
( Samrawit, 32,1.64) next to
Current – Quiz 5%
Start_ptr current

Ahmad Mokonnon Semira


23 42 26
1.75 1.5 1.7

Eden Hadera
21 22
1.45 1.75

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

41
Definitions
struct Book
{
int BookId;
bool BookRes;
bool BookBor;
Book *next, *prev;
};
Book *HULibBookptr=NULL; //first node

42
Storing and accessing
Data files

(*HULibBookptr).BookID=3;
(*HULibBookptr).BookRes=true;
(*HULibBookptr).BookBor =false;
(*HULibBookptr).next=NULL;
(*HULibBookptr).prev=NULL;

43
Adding a node to the end
of a list
Book *NewBookptr, *LastBookptr= NULL;
NewBookptr= new Book;
NewBookptr->BookId=BI;
NewBookptr->BookRes=BR; HULibBookptr LastBookptr
NewBookptr->BookBor=BB;
NewBookptr->next=NULL;
NewBookptr->prev=NULL
if(HULibBookptr==NULL) Data1 Data2 Data3
{ Next Next Next
HULibBookptr=NewBookptr; prev prev
LastBookptr= HULibBookptr; prev
}
else
{
LastBookptr->Next=NewBookptr;
NewBookptr->prev=LastBookptr;
LastBookptr=LastBookptr->Next;
}

44
Deleting a node
if(HULibBookptr!=NULL)
if(currBookptr==HULibBookptr) //first node
{ HULibBookptr=HULibBookptr->next;
HULibBookptr->prev=NULL;
}else if(currBookptr->next==NULL);// last
node
PrevBookptr->next=NULL;
else //middle node
{ PrevBookptr->Next=currBookptr->next;
nextBookptr->prev=PrevBookptr;
}
delete currentBookptr;

45
Inserting a node
prevbookptr->next=currBookptr;
currBookptr->prev=prevbookptr;
currBookptr->next=nextBookptr;
nextBookptr->prev=currBookptr;

HUBookptr

1 2 4 5
NextBookptr
PrvBookptr

3 46
currBookptr
Sorting Linked Lists

Book *i, *j; //simple sort


for(i=HUBookptr;i->next!=NULL;i=i-
>Next)
for(j=i->next;j!=NULL;j=j->next)
If(i->BookId>j->BookId)
Swap(i,j);
Exercise:
Write the function swap(Book *i, Book *j)
using the pointer and value function
parameter pass approaches.
47
searching
Book *i;
i=start_ptr;
found =false;
while((i!=NULL) &&(found==false))
{ if(i->name==searchkey)
{ found=true;
break;
}else
i=i->nxt;
}
return found;
48
Circular Lists

In some situations, a linked list that forms a


ring is needed; i.e. there are no null pointers to
indicate the end of the list, and each node has a
successor node
In terms of the data structure employed,
circular linked lists do not differ from non-
circular linked lists: they can be either singly
linked or doubly linked

49

we only need one pointer into the list.
Because the list is circular, it does not really
make sense to talk about a beginning and an
end to the list, we only need a single pointer
into any node in the list.

Start_ptr

node1 node2 node3

50

You might also like