0% found this document useful (0 votes)
14 views91 pages

Chap IV Linked List Part -1

The document provides an overview of linked lists, including their structure, types (singly, doubly, circular), and operations such as creation, traversal, searching, insertion, and deletion. It highlights the advantages of linked lists over arrays, particularly in terms of dynamic memory allocation and efficient insertions and deletions. Additionally, it includes algorithms and C code examples for implementing and manipulating 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)
14 views91 pages

Chap IV Linked List Part -1

The document provides an overview of linked lists, including their structure, types (singly, doubly, circular), and operations such as creation, traversal, searching, insertion, and deletion. It highlights the advantages of linked lists over arrays, particularly in terms of dynamic memory allocation and efficient insertions and deletions. Additionally, it includes algorithms and C code examples for implementing and manipulating 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/ 91

LINKED LIST

III SEM DIPLOMA IN COMPUTER


ENGINEERING
Contents:
4.1 Introduction, Singly link list
Representation of link list in memory.
4.2 Creating, Traversing, Searching in Sorted
and Unsorted Linked List.
4.3 Memory allocation, garbage Collection.
4.4 Inserting into linked list, Deleting from a
linked list.
4.5 Header links list, Two-way list,
Implementation of link list.
LINKED LIST
A linked list or one way list is a linear
collection of data elements, called nodes,
where the linear order is given by means of
“pointers”. Each node is divided into two
parts.
Ø The first part contains the information of
the element.
Ø The second part called the link field
contains the address of the next node in the
list.
To see this more clearly lets look at an
LINKED LIST
LINKED LIST
The Head is a special pointer variable
which contains the address of the first
node of the list.
If there is no node available in the list then
Head contains NULL value that means,
List is empty.
The left part of the each node represents the
information part of the node, which may
contain an entire record of data (e.g. ID,
name, marks, age etc). the right part
represents pointer/link to the next node. The
next pointer of the last node is null pointer
Representation of Linked list in memory
Linked list is maintained in memory by two
linear arrays: INFO and LINK such that
INFO [K] and LINK [K] contain
respectively the information part and the
next pointer field of node of LIST.
LIST also requires a variable name such
as START which contains the location of the
beginning of the list and the next pointer
denoted by NULL which indicates the end of
the LIST.
Representation of Linked list in memory
Types of linked lists
– Singly linked list
 Begins with a pointer to the first node
 Terminates with a null pointer
 Only traversed in one direction
– Circular, singly linked
 Pointer in the last node points back to the first
node
– Doubly linked list
 Two “start pointers” – first element and last
element
 Each node has a forward pointer and a backward
pointer
 Allows traversals both forwards and backwards
Types of linked lists
– Circular, doubly linked list
 Forward pointer of the last node points to the
first node and backward pointer of the first
node points to the last node
– Header Linked List
 Linked list contains a header node that
contains information regarding complete linked
list.
The Operations on the Linear Lists
1- Search: This operation involves the searching
of an element in the linked list.
2- Addition(Inserting) : To add new node to data
structure.
3- Deletion : To delete a node from data structure.
4- Merge : To merge two structures or more to
constituting one structure.
5- Split : To divide data structure to two
structures or more.
6- Counting : counting some of items or nodes in
data structure.
Comparison of Linked List and Array
Advantages
List of data can be stored in arrays but linked
structures (pointers) provide several
advantages:
A linked list is appropriate when the number of
data elements to be represented in data
structure is unpredictable.
It also appropriate when there are frequently
insertions & deletions occurred
Representation of multiple Linked list in
memory
Two different linked lists are simultaneously
maintained in the memory.
There is no ambiguity in traversing through
the list because each list maintains a separate
Start pointer, which gives the address of the
first node of their respective linked lists.
The rest of the nodes are reached by looking
at the value stored in the NEXT.
Representation of multiple Linked list in
memory
By looking at the figure, we can conclude
that roll numbers of the students who have
opted for Biology are S01, S03, S06, S08,
S10, and S11.

Similarly, roll numbers of the students who


chose Computer Science are S02, S04, S05,
S07, andS09.
Similarly suppose a
brokerage firm has four
brokers and each broker
has its own list of
customers. here all the 4
list of customers in
maintained in the same
array CUSTOMER and an
array LINK contains the
next pointer fields of the
nodes of the list. There
also contains an array
BROKER and pointer array
POINT such that POINT[K]
points to the beginning of
the list of the customers of
BROKER[K]
struct node
{
int info;
struct node *next;
};
struct node *start=NULL;
TRAVERSING A LIST
Traversing a linked list means accessing the nodes
of the list in order to perform some processing on
them.
Remember a linked list always contains a pointer
variable START which stores the address of the first
node of the list.
End of the list is marked by storing NULL or –1 in
the NEXT field of the last node.
For traversing the linked list, we also make use of
another pointer variable PTR which points to the
node that is currently being accessed. The algorithm
to traverse a linked list is shown in following Fig
TRAVERSING A LIST

•In this algorithm, we first initialize PTR with the address of


START. So now, PTR points to the first node of the linked list.
•Then in Step 2, a while loop is executed which is repeated
till PTR processes the last node, that is until it encounters
NULL.
•In Step 3, we apply the process (e.g., print) to the current
node, that is, the node pointed by PTR.
• In Step 4, we move to the next node by making the PTR
variable point to the node whose address is stored in the
An algorithm to count the
number of nodes in a linked list

•Let us now write an algorithm to count the number of nodes in


a linked list.
•To do this, we will traverse each and every node of the list and
while traversing every individual node, we will increment the
counter by 1.
•Once we reach NULL, that is, when all the nodes of the linked
list have been traversed, the final value of the counter willbe
TRAVERSING A LIST
Let us Recall- Linked List
Types of Lists
Depending on the way in which the links are
used to maintain adjacency, several different
types of linked lists are possible.

Linear singly-linked list (or simply linear list)


head  One we have discussed so far.

A B C
Circular linked list
 The pointer from the last element in the list points

back to the first element.


head

A B C
Doubly linked list
 Pointers exist between adjacent nodes in both

directions.
 The list can be traversed either forward or

backward.
head tail
 Usually two pointers are maintained to keep track

of the list, head and tail.


A B C
List is an Abstract Data Type
• What is an abstract data type?
– It is a data type defined by the user.
– Typically more complex than simple data types
like int, float, etc.
• Why abstract?
– Because details of the implementation are
hidden.
– When you do some operation on the list, say
insert an element, you just call a function.
– Details of how the list is implemented or how
the insert function is written is no longer
required.
OPERATIONS ON LINKED LIST
Keeping track of a linked list:
Must know the pointer to the first element of
the list (called start, head, etc.).

Linked lists provide flexibility in allowing the


items to be rearranged efficiently.
Insert an element.
Delete an element.
OPERATIONS ON LINKED LIST
Two important points to remember:

head points to the first node of the linked list

next pointer of last node is NULL, so if next of


current node is NULL, we have reached end of
linked list.
Creating a Linked List
A node in a linked list is self referential
structure.
So we define a node as a structure.

typedef struct node


{
int data;
struct node *next;
}node;
//Structure example
#include <stdio.h>
struct person
{
int age;
float weight;
}p[5];
void main()
{
int i=0;
/*printf(“Enter age and weight of a person1”);
scanf(“%d%f”,&p1.age,&p1.weight);
printf(“Enter age and weight of a person2”);
scanf(“%d%f”,&p2.age,&p2.weight);*/
for(i=0;i<=4;i++)
{
printf(“Enter age and weight of a person %d”,i+1);
scanf(“%d%f”,&p[i].age,&p[i].weight);
}

}
//Structure Pointer example
#include <stdio.h>
struct person
{
int age;
float weight;
};
void main()
{
struct person p;
struct person *ptr;//structure pointer declaration
ptr=&p; // structure pointer initialization
printf(“Enter age and weight of a person1”);
scanf(“%d%f”,&ptr->age,&ptr->weight);
printf(“%d%f”,ptr->age,ptr->weight);
}
Creating a Linked List
Now we need to allocate the memory for
node dynamically as :
For head node:
HEAD=(node*)malloc(sizeof(node));

For other nodes:


P->next=(node*)malloc(sizeof(node));
Creating a Linked List
In order to move to the next node we write :
P=P->next;
where p is the current node that is being accessed

In order to assign value to the data field we


write:
HEAD->data=10;
P->data=20;

If it’s a last node then we write:


P->next=NULL;
Here is a complete program for creating a
linked list:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
void main()
{
node *HEAD , *P;
int n,x,i;
clrscr();
printf("Enter no. of Items to be inserted in the linked list");
scanf("%d",&n);
HEAD=(node*)malloc(sizeof(node));
HEAD->next=NULL;
P=HEAD;
for(i=1;i<n;i++)
{
P->next=(node*)malloc(sizeof(node));
P=P->next;
P->next=NULL;
scanf("%d",&(P->data));
}
P=HEAD;
for(i=0;i<n;i++)
{
printf("%d\t",P->data);
P=(P->next);
}
getch();
}
 Program to create a linked list
Creating a Linked List Using Function
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node * create(int);
void main()
{
node *HEAD;
int n;
HEAD=NULL; //List is empty
clrscr();
printf("Enter no. of Items to be inserted in the linked list");
scanf("%d",&n);
HEAD=create(n); // instead of HEAD=(node*)malloc(sizeof(node));
Creating a Linked List Using Function
node *create(int n)
{
Node *head,*P;
int i;
head=(node*)malloc(sizeof(node));
head->next=NULL;
scanf(“%d”,&(head->data));
P=head;
for(i=1;i<n;i++)
{
P->next=(node*)malloc(sizeof(node));
P=P->next;
P->next=NULL;
scanf("%d",&(P->data));
}
return (head);
}

getch();
TRAVERSING A LIST

•In this algorithm, we first initialize PTR with the address of


START. So now, PTR points to the first node of the linked list.
•Then in Step 2, a while loop is executed which is repeated
till PTR processes the last node, that is until it encounters
NULL.
•In Step 3, we apply the process (e.g., print) to the current
node, that is, the node pointed by PTR.
• In Step 4, we move to the next node by making the PTR
variable point to the node whose address is stored in the
How to traverse a linked list
Displaying the contents of a linked list is very
simple. We keep moving the temp node to the
next one and display its contents.
When temp is NULL, we know that we have
reached the end of linked list so we get out of
the while loop.
struct node *temp = head;
printf("\n\nList elements are - \n");
while(temp != NULL)
{ printf("%d --->",temp->data);
temp = temp->next;
}
The output of this program will be:
List elements are - 1 --->2 --->3 --->
An algorithm to count the
number of nodes in a linked list

•Let us now write an algorithm to count the number of nodes in


a linked list.
•To do this, we will traverse each and every node of the list and
while traversing every individual node, we will increment the
counter by 1.
•Once we reach NULL, that is, when all the nodes of the linked
list have been traversed, the final value of the counter willbe
Counting number of nodes in Linked list
int count (node *P)
{
int i;
i=0;
while(P!=NULL)
{
i=i+1;
P=P->next;
}
return(i);
}
Searching in Linked List
Let list be a linked list in the memory and a
specific ITEM of information is given to search.
If ITEM is actually a key value and we are
searching through a LIST for the record
containing ITEM, then ITEM can appear only
once in the LIST.
Search for wanted ITEM in List can be
performed by traversing the list using a pointer
variable PTR and comparing ITEM with the
contents PTR->INFO of each node, one by one
of list.
Searching in Linked List
C function for searching an element x in a linked list
referenced by the pointer head. Function returns 1 if
search ends in a success, otherwise, the function returns 0
int search1(node *head, int x)
{
node *P;
P=head;
While(P!=NULL)
{
if(P->data==x)
return(1);
P=P->next;
}
return(0);
}
C function for searching an element x in a linked list
referenced by the pointer head. Function returns address
of the node if search ends in a success, otherwise, the
function returns NULL
int search2(node *head, int x)
{
node *P;
P=head;
While(P!=NULL)
{
if(P->data==x)
return(P);
P=P->next;
}
return(NULL);
}
C function for searching an element x in a linked list
referenced by the pointer head. Function returns location
of the node if search ends in a success, otherwise, the
function returns -1
int search3(node *head, int x)
{
int i=1;
node *P;
P=head;
While(P!=NULL)
{
if(P->data==x)
return(i);
i++;
P=P->next;
}
return(-1);
}
Searching in sorted Linked List
Algorithm: SRCHSL (INFO, LINK, START,
ITEM, LOC)
LIST is sorted list (Sorted in ascending order)
in memory. This algorithm finds the location
LOC of the node where ITEM first appears in
LIST or sets LOC=NULL.
Searching in sorted Linked List
1.Set PTR:= START
2. Repeat while PTR ≠ NULL
If ITEM > INFO[PTR], then:
Set PTR := LINK[PTR]
Else If ITEM = INFO[PTR], then:
Set LOC := PTR
Return
Else Set LOC:= NULL
Return
[End of If structure]
[End of step 2 Loop]
3. Set LOC:= NULL
4. Return
Searching in sorted Linked List
int search_sorted(node *head, int x)
{
node *P;
P=head;
While(P!=NULL)
{
if(P->data==x)
return(1);

if(P->data>x)
return(0);

P=P->next;
}
Return(0);
}
Memory Allocation and
De-allocation for a Linked
List and Garbage
Collection
Memory Allocation and De-allocation for
a Linked List
 We have seen how a linked list is represented in the memory. If
we want to add a node to an already existing linked list in the
memory, we first find free space in the memory and then use it to
store the information.
 For example, consider the linked list shown in Fig. The linked list
contains the roll number of students, marks obtained by them in
Biology, and finally a NEXT field which stores the address of the
next node in sequence.
 Now, if a new student joins the class and is asked to appear for
the same test that the other students had taken, then the new
student’s marks should also be recorded in the linked list.
 For this purpose, we find a free space and store the information
there. In Fig. 6.5 the grey shaded portion shows free space, and
thus we have 4 memory locations available. We can use any one
of them to store our data.
Memory Allocation and De-allocation for
a Linked List
Now, the question is which part of the memory
is available and which part is occupied? When
we delete a node from a linked list, then who
changes the status of the memory occupied by
it from occupied to available?
The answer is the operating system.
However, let us briefly discuss the basic
concept behind it. The computer maintains a
list of all free memory cells. This list of
available space is called the free pool.
Memory Allocation and De-allocation for
a Linked List
We have seen that every linked list has a pointer
variable START which stores the address of the
first node of the list. Likewise, for the free pool
(which is a linked list of all free memory cells), we
have a pointer variable AVAIL which stores the
address of the first free space.
Now, when a new student’s record has to be
added, the memory address pointed by AVAIL will
be taken and used to store the desired
information. After the insertion, the next available
free space’s address will be stored in AVAIL.
For example, in Fig. 6.6, when the first free memory space is
utilized for inserting the new node, AVAIL will be set to contain address 6.
Memory Allocation and De-allocation for
a Linked List
This was all about inserting a new node in an already
existing linked list. Now, we will discuss deleting a
node or the entire linked list. When we delete a
particular node from an existing linked list or delete
the entire linked list, the space occupied by it must be
given back to the free pool so that the memory can be
reused by some other program that needs memory
space.
The operating system does this task of adding the
freed memory to the free pool. The operating system
will perform this operation whenever it finds the CPU
idle or whenever the programs are falling short of
memory space.
Memory Allocation and De-allocation for
a Linked List
The operating system scans through all the
memory cells and marks those cells that are
being used by some program.
Then it collects all the cells which are not
being used and adds their address to the free
pool, so that these cells can be reused by
other programs.
This process is called garbage collection.
INSERTING INTO LINKED LIST
How to add elements to linked list

In this section, we will see how a new node is


added into an already existing linked list. We
will take four cases and then see how
insertion is done in each case.
Case 1: The new node is inserted at the
beginning.
Case 2: The new node is inserted at the end.
Case 3: The new node is inserted after a given
node.
Case 4: The new node is inserted before a
given node.
OVERFLOW
Before we describe the algorithms to perform
insertions in all these four cases, let us first
discuss an important term called OVERFLOW.
Overflow is a condition that occurs when
AVAIL = NULL or no free memory cell is
present in the system.
When this condition occurs, the program
must give an appropriate message.
Inserting a Node at the Beginning of a
Linked List
Consider the linked list shown in following
Fig. Suppose we want to add a new node with
data 9 and add it as the first node of the list.
Then the following changes will be done in
the linked list.
Inserting a Node at the Beginning of a
Linked List
Algorithm to insert a new node at
the beginning
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL NEXT
Step 4: SET DATA = VAL
Step 5: SET NEW_NODE NEXT = START
Step 6: SET START = NEW_NODE
Step 7: EXIT
Inserting a Node at the Beginning of a
Linked List
Note the following two steps:
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL -> NEXT
These steps allocate memory for the new
node. In C, there are functions like malloc(),
alloc, and calloc() which automatically do the
memory allocation on behalf of the user.
Add to beginning
Allocate memory for new node
Store data
Change next of new node to point to head
Change head to point to recently created
node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
C program segment for Inserting a Node at the
Beginning of a Linked List
// Create a new node and inserts at the beginning of the linked list.

void insertNodeAtBeginning(int data)


{
struct node *newNode;

newNode = (struct node*)malloc(sizeof(struct node));

if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; // Link data part
newNode->next = head; // Link address part

head = newNode; // Make newNode as first node

printf("DATA INSERTED SUCCESSFULLY\n");


}
}
C program for Inserting a Node at the
Beginning of a Linked List
Inserting a Node at the End of a Linked
List
Inserting a Node at the End of a Linked List Consider the linked list shown in
following fig. Suppose we want to add a new node with data 9 as the last node
of the list. Then the following changes will be done in the linked list.
Inserting a Node at the End of a Linked List
Figure shows the algorithm to
insert a new node at the end of a
linked list.
• In Step 6, we take a pointer
variable PTR and initialize it with
START. That is, PTR now points to
the first node of the linked list.
•In the while loop, we traverse
through the linked list to reach the
last node. Once we reach the last
node, in Step 9, we change the
NEXT pointer of the last node to
store the address of the new node.
• Remember that the NEXT field of
the new node contains NULL,
which signifies the end of the linked
list.
Add to end
Program segment for Inserting a Node at the End of a Linked List
//Create a new node and inserts at the end of the linked list.
void insertNodeAtEnd(int data)
{
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
Else
{
newNode->data = data; // Link the data part
newNode->next = NULL;
temp = head;
// Traverse to the last node
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode; // Link address part
printf("DATA INSERTED SUCCESSFULLY\n");
}
C program for Inserting a Node at the
End of a Linked List
Illustration: Insertion
A B C

tmp X Item to be
inserted

A B C

curr

X
Pseudo-code for insertion
typedef struct nd {
struct item data;
struct nd * next;
} node;

void insert(node *curr)


{
node * tmp;

tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
Add to middle
Allocate memory and store data for new node
Traverse to node just before the required
position of new node
Change next pointers to include new node in
between
struct node *newNode; newNode =
malloc(sizeof(struct node));
newNode->data = 4;
struct node *temp = head;
for(int i=2; i < position; i++)
{
if(temp->next != NULL)
{
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next
How to delete from a linked list
You can delete either from beginning, end or
from a particular position.
Illustration: Deletion
Item to be deleted

A B C

tmp
curr

A B C
Pseudo-code for deletion
typedef struct nd {
struct item data;
struct nd * next;
} node;

void delete(node *curr)


{
node * tmp;
tmp=curr->next;
curr->next=tmp->next;
free(tmp);
}
Delete from beginning

head = head->next;
Delete from end

Traverse to second last element


Change its next pointer to null
struct node* temp = head;
while(temp->next->next!=NULL)
{
temp = temp->next;
}
temp->next = NULL;
Delete from middle
Traverse to element before the element to be
deleted
Change next pointers to exclude the node from
the chain
for(int i=2; i< position; i++)
{
if(temp->next!=NULL)
{
temp = temp->next;
}
}
temp->next = temp->next->next;
Creating a node
struct node
{
int data; // A simple node of a linked
list
node*next;
}*start; //start points at the first node
start=NULL ; initialised
to
node* create( int num) //say num=1 is passed from main
{
node*ptr; ptr= new node; //memory allocated dynamically
if(ptr==NULL)
‘OVERFLOW’ // no memory available
exit(1);
Else
{
ptr->data=num;
ptr->next=NULL;
return ptr;
}
}
To be called from main() as:-
void main()
{
node* ptr;
int data;
cin>>data;
ptr=create(data);
}
CREATING A LINKED LIST
In C, we can implement a linked list using the
following code:
struct node
{
int data;
struct node *next;
};
 In C, we can use void pointer and function pointer to implement the
same functionality. The great thing about void pointer is it can be
used to point to any data type. Also, size of all types of pointers is
always is same, so we can always allocate a linked list node. Function
pointer is needed process actual content stored at address pointed by
void pointer.
 Following is a sample C code to demonstrate working of generic
linked list.
 // C program for generic linked list
 #include<stdio.h>
 #include<stdlib.h>

 /* A linked list node */
 struct Node
{
 // Any data type can be stored in this node
 void *data;

 struct Node *next;
 };

You might also like