UNIT1
UNIT1
UNIT 1: INTRODUCTION
Data Structures
A data structure is an arrangement of data elements. Data Structure can be
defined as the group of data elements which provides an efficient way of
storing and organizing data in the computer so that it can be used efficiently.
Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
Data Structures are widely used in almost every aspect of Computer Science
i.e. Operating System, Compiler Design, Artificial Intelligence, Graphics and
many more.
Data Structures are the main part of many computer science algorithms
as they enable the programmers to handle the data in an efficient way. It plays
a vital role in enhancing the performance of a software or a program as the
main function of the software is to store and retrieve the user’s data as
fast as possible
Data structures are the building blocks of any program or the software.
Choosing the appropriate data structure for a program is the most crucial
task for a programmer.
1.2 Needs
As applications are getting complex and amount of data is increasing day by day,
the following issues might be araised:
1. Processor speed: To handle very large amount of data, high speed processing
is required, but as the data is growing day by day to the billions of files per
entity, processor may fail to deal with that much amount of data.
2. Data Search: Consider an inventory size of 106 items in a store; if our
application needs to search for a particular item, it needs to traverse 106 items
every time, results in slowing down the search process.
3. Multiple requests: If thousands of users are searching the data
simultaneously in a web server, it fails to process the requests.
In order to solve the above problems, data structures are used. Data is organized to
form a data structure in such a way that all items are not required to be searched and
required data can be searched instantly.
Data structures are important as they provide the mechanism for defining what
we can do with our data. Also, data structures can have certain performance
characteristics, for example retrieving the value of an array at a specified index
will always be the same no matter how small or large the index is.
Data structure is a particular way of storing and organizing information in a
computer so that it can be retrieved and used most productively. Using data
structures, from simple arrays to more complex trees, hash tables, or custom data
structures, allows your code to both be more organized and extensible.
Using an array, which can either be created to hold the required number of
elements or extended to hold more after its first created keeps you from having
to rewrite your code each time the number of data items changes.
Using an appropriate data structure allows you to design algorithms based on the
relationships between the data elements rather than some fixed ordering, giving
you more flexibility. Different kinds of data structures are meant for different
kinds of applications, and some are highly specialized to specific tasks.
and make possible the management of huge amounts of data, such as large
integrated collection of databases.
3. Some programming languages emphasize data structures, rather than algorithms,
A data structure is called linear if all of its elements are arranged in the linear
order. In linear data structures, the elements are stored in non-hierarchical way
where each element has the successors and predecessors except the first and last
element. Collection of nodes which are logically adjacent in which logical adjacency
is maintained by pointers. Linear data structures can be constructed as a continuous
arrangement of data elements in the memory. It can be constructed by using array
data type. In the linear Data Structures the relationship of adjacency is maintained
between the Data elements. In linear data structure the elements are stored in
sequential order.
Types of Linear Data Structures are given below:
The elements of array share the same variable name but each one carries a different
index number known as subscript. The array can be one dimensional, two
dimensional or multidimensional.The individual elements of the array age are:
Linked List: Linked list is a linear data structure which is used to maintain a list in
the memory. It can be seen as the collection of nodes stored at non-contiguous memory
locations. Each node of the list contains a pointer to its adjacent node. It is a
collection of data of same data type but the data items need not be stored in
consecutive memory locations.
Stack: Stack is a linear list in which insertion and deletions are allowed only at one
end, called top. It is a Last-In-First-Out linear data structure.
Queue: Queue is a linear list in which elements can be inserted only at one end called
rear and deleted only at the other end called front. It is a First-In-First-Out Linear
data structure.
Trees: Trees are multilevel data structures with a hierarchical relationship among
its elements known as nodes. The bottommost nodes in the hierarchy are called leaf
node while the topmost node is called root node. Each node contains pointers to point
adjacent nodes. Trees are used to represent data that has some hierarchical relationship
among the data elements.
Tree data structure is based on the parent-child relationship among the nodes.
Each node in the tree can have more than one child except the leaf nodes whereas
each node can have at most one parent except the root node. Trees can be classified
into many categories which will be discussed later in this tutorial.
Graphs: Graphs can be defined as the pictorial representation of the set of elements
(representesd by vertices) connected by the links known as edges. A graph is different
from tree in the sense that a graph can have cycle while the tree cannot have the one.
Graph is used to represent data that has relationship between pair of elements not
necessarily hierarchical in nature. For example electrical and communication
networks, airline routes, flow chart, graphs for planning projects.
2. Delete elements
The following are the operations performed on any data structure.They are
1. Insertion: Insertion can be defined as the process of adding the elements to the
data structure at any location. A new element is inserted into an existing data structure.
2. Deletion: The process of removing an element from the data structure is called
Deletion. We can delete an element from the data structure at any random
location.An existing element is deleted from a data structure.
3. Traversal: Every data structure contains the set of data elements. Traversing the data
structure means visiting each element of the data structure in order to perform some
specific operation like searching or sorting. Every element of a data structure is visited
exactly once and a process is applied.
4. Searching: The process of finding the location of an element within the data structure
is called Searching. There are two algorithms to perform searching, Linear Search and
Binary Search. A data structure is searched for locating a given element, if available.
The procedure returns the location if the element is available. Otherwise a Not
available message or equivalent is returned.
5. Sorting: The process of arranging the data structure in a specific order is known as
Sorting. There are many algorithms that can be used to perform sorting, for example,
insertion sort, selection sort, bubble sort, etc. The elements of a given data structure
are arranged in ascending or descending order.
6. Merging: When two lists List A and List B of size M and N respectively, of similar
type of elements, clubbed or joined to produce the third list, List C of size (M+N), then
this process is called merging. It is used to combine the data items of two sorted files
into single file in the sorted form.
Searching and sorting are not basic operations but complex procedures that can be
done using the basic operations 1, 2 and 3. But, these are very frequently used in
most applications. Any other complex application can be built in terms of these five
operations. All basic operations and procedures are described by a simple informal
notation called as algorithm.
Inserting It is used to add a new data item in the given collection of data items.
Eg: Suppose we have an array of size 20 used to store marks obtained by the students
in Computer Science subject. If we have already added
15 students’ marks according to an ascending order, then we can add another student
marks at appropriate place, by shifting the already stored element accordingly. Then
it is called Insertion operation.
Deleting – It is used to delete an existing data item from the given collection of data
items.
Eg: Suppose we have an array of size 20 used to store marks obtained by the students
in Computer Science subject. If we have already added
15 students’ marks according to an ascending order, then we can delete one student’s
marks from any place, by shifting the already stored elements accordingly. Then
it is called Deletion operation.
Traversing – It is used to access each data item exactly once so that itcan be processed.
Eg: Suppose we have an array of 20 students’ average makes, and if we need to
calculate the average of group, we visit (read) each individual average and accumulate
(sum) them. Then we will find the array is visited once and only once. Then it is
traversing of an array.
Searching – It is used to find out the location of the data item if it exists in the
given collection of data items.
Eg: Suppose we have an array of size 10 and assume elements stored are 1, 2, 3, 23,
34, 54, 56, 21, 32, 33 and assume we want to search the number 23. So here the
number ‘23’ is key element. The key is searched through the array starting from the
first element till end. When it is compared with the fourth element in it is present in
the list (array) of numbers. So search is successful. This type of searching is called as
Linear
Search because the last element. In order to apply linear search, the list may not be in
any particular order but when binary search is applied the list must be an ordered one.
Sorting – It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of alpha
numeric data.
Eg: Suppose we have an array of size 10 and assume elements stored are 1, 2, 3,
23, 34, 54, 56, 21, 32, 33. The elements of the array are not in proper order. If they
are arranged in ascending order the list (array) becomes1, 2, 3, 21, 23, 32, 34, 54,
56.
Merging – It is used to combine the data items of two sorted files into single file in
the sorted form.
Eg: Suppose we have a list of size 6, containing the elements 1, 2, 3, 4,
71, 87 and we have another list of size 5, containing the elements 9, 13, 21, 65, 67.
Here both the lists are in ascending order. We can produce the third list of size 11
that will also be in ascending order, containing the element 1, 2, 3, 4, 9, 13, 21, 65,
67, 71, 87. The third list is called the merged list of first and second lists. In order to
merge two lists into single list one needs to compare each element from both the lists
and one of them will go the merged list.
1.5 ARRAYS
Array Representation
The number of data items chunked together into a unit is known as data structure.
When the data structure consists simply a sequence of data items, the data structure of
this simple variety is referred as an array. An array is the most fundamental data
structure from which other data structures maybe built such as stack, queue, strings
etc. It is designed to hold number of objects (items) of same types. It is an efficient
data structure for storage and accessing of objects.
Definition: Array is a collection of homogenous (same data type) data elements that
are stored in contiguous memory locations.
Homogeneity and physical contiguity have a purpose. Since, each element
occupies the same memory space and all are continually placed the physical address
of each element can be calculated using a common formula. Let each element occupy
w word lengths. The first element’s starting address is the address A. The second
element’s starting address is A + w. In general, the ith elements starting address is A
+ (i-1) * w. The physical address of any element is computed by the same formula,
which means that it takes same amount of time. Thus the access is same for all
elements of an array. It’s random- a c c e s s memory (RAM).
Arrays are used for storing sequential data. For example:
✱ Matrices
Array Syntax
Syntax to declare an array:
✱ dataType [ ] arrayName;
Example:
int [ ] x; x=new int [10]; (or) int [] x=new int [10];
Array Initialization
The values of an array can be initialized as follows,
Example 1:
int [] j=new int [1]; j[0] =10;(or)int [] j= {25};
Example 2:
int [] myarray= {5, 10};
Characteristics of an Array
The following are the characteristics of an array data structure.
(i) Array stores elements of same data type.
(ii) The elements of an array are stored in subsequent memory locations.
(iii) The name of array represents the starting address of the elements.
(iv) When data objects are stored in array, individual objects are selected by an index.
(v) By default an array index starts from 0 and ends with (n-1). Index is also referred as
subscripts.
(vi) The size of the array is mentioned at the time of declaring array.
(vii) While declaring 2D array, number of columns should be specified whereas for
number of rows there is no such rule.
(viii) Size of array can’t be changed at run time.
Array Types
(i) One-Dimensional Array or Linear arrays
(ii) Multi-Dimensional Array
Multi-Dimensional Array
The array with more than one dimension is referred as multi-dimensional array.
All multi- dimensional arrays use a linear equation very similar to that of the one
dimensional array for computing the address of an element. The simplest form of the
multi-dimensional array is the two-dimensional array. It is useful for matrices, 3D
graphics etc.
bool false
char 0
int 0
float 0.0
double 0.0f
void
wchar_t 0
In C, when an array is initialized with size, then it assigns defaults values to its
elements in following order.
Algorithm
Following is an algorithm to insert elements into a Linear Array until we reach the end
of the array –
1. Start
2. Create an Array of a desired datatype and size.
3. Initialize a variable 'i' as 0.
4. Enter the element at ith index of the array.
5. Increment i by 1.
6. Repeat Steps 4 & 5 until the end of the array.
7. Stop
Example
Here, we see a practical implementation of insertion operation, where we add data at
the end of the array −
#include <stdio.h>
int main(){
int LA[3] = {}, i;
printf("Array Before Insertion:\n");
for(i = 0; i < 3; i++)
printf("LA[%d] = %d \n", i, LA[i]);
printf("Inserting Elements.. \n");
printf("The array elements after insertion :\n"); // prints array values
for(i = 0; i < 3; i++) {
LA[i] = i + 2;
printf("LA[%d] = %d \n", i, LA[i]);
}
return 0;
}
Output
Array Before Insertion:
LA[0] = 0
LA[1] = 0
LA[2] = 0
Inserting elements..
Array After Insertion:
LA[0] = 2
LA[1] = 3
LA[2] = 4
LA[3] = 5
LA[4] = 6
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that
K<=N. Following is the algorithm to delete an element available at the Kth position of
LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Example
Following are the implementations of this operation in C programming languages
#include <stdio.h>
void main(){
int LA[] = {1,3,5};
int n = 3;
int i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
printf("LA[%d] = %d \n", i, LA[i]);
for(i = 1; i<n; i++) {
LA[i] = LA[i+1];
n = n - 1;
}
printf("The array elements after deletion :\n");
for(i = 0; i<n; i++)
printf("LA[%d] = %d \n", i, LA[i]);
}
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
The array elements after deletion :
LA[0] = 1
LA[1] = 5
Searching an element in the array using a key; The key element sequentially compares
every value in the array to check if the key is present in the array or not.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that
K<=N. Following is the algorithm to find an element with a value of ITEM using
sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Example
Following are the implementations of this operation in C programming languages –
#include <stdio.h>
void main(){
int LA[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
for(i = 0; i<n; i++) {
if( LA[i] == item ) {
printf("Found element %d at position %d\n", item, i+1);
}
}
}
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Found element 5 at position 3
This operation traverses through all the elements of an array. We use loop statements
to carry this out.
Algorithm
Following is the algorithm to traverse through all the elements present in a Linear
Array –
1 Start
2. Initialize an Array of certain size and datatype.
3. Initialize another variable ‘i’ with 0.
4. Print the ith value in the array and increment i.
5. Repeat Step 4 until the end of the array is reached.
6. End
Example
Following are the implementations of this operation in C programming languages –
#include <stdio.h>
int main(){
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Update operation refers to updating an existing element from the array at a given index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such that
K<=N. Following is the algorithm to update an element available at the Kth position
of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
Example
Following are the implementations of this operation in C programming languages –
#include <stdio.h>
void main(){
int LA[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
LA[k-1] = item;
printf("The array elements after updation :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after updation :
LA[0] = 1
LA[1] = 3
LA[2] = 10
LA[3] = 7
LA[4] = 8
This operation displays all the elements in the entire array using a print statement.
Algorithm
Consider LA is a linear array with N elements. Following is the algorithm to display
an array elements.
1. Start
2. Print all the elements in the Array
3. Stop
Example
#include <stdio.h>
int main(){
int LA[] = {1,3,5,7,8};
int n = 5;
int i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
1.5 LINKED LISTS
Linked lists and arrays are similar since they both store collections of data.
Array is the most common data structure used to store collections of elements. Arrays
are convenient to declare and provide the easy syntax to access any element by its index
number. Once the array is set up, access to any element is convenient and fast.
makes the programmers to allocate arrays, which seems "large enough" than required.
• Inserting new elements at the front is potentially expensive because existing
strengths and weaknesses, but they happen to be strong where arrays are weak.
Generally array's allocates the memory for all its elements in one block whereas
linked lists use an entirely different strategy. Linked lists allocate memory for each
element separately and only when necessary.
Linked List Concepts:
A linked list is a non-sequential collection of data items. It is a dynamic data
structure. For every data item in a linked list, there is an associated pointer that would
give the memory location of the next data item in the linked list. The data items in the
linked list are not in consecutive memory locations. They may be anywhere, but the
accessing of these data items is easier as each data item contains the address of the next
data item.
Types of Linked Lists:
Basically we can put linked lists into the following four items:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.
A single linked list is one in which all nodes are linked together in some sequential
manner. Hence, it is also called as linear linked list.
A double linked list is one in which all nodes are linked together by multiple links
which helps in accessing both the successor node (next node) and predecessor node
(previous node) from any arbitrary node within the list. Therefore each node in a
double linked list has two link fields (pointers) to point to the left node (previous) and
the right node (next). This helps to traverse in forward direction and backward
direction.
A circular linked list is one, which has no beginning and no end. A single linked list
can be made a circular linked list by simply storing address of the very first node in
the link field of the last node.
Comparison between array and linked list:
Static representation
In static representation of a single linked list, two arrays are maintained: one array for
data and the other for links. The static representation of the linked list in Figure 5.2 is
shown in Figure 5.3.
Two parallel arrays of equal size are allocated which should be sufficient to store
the entire linked list. Neverthemless this contradicts the idea of the linked list (that is
non-contagious location of elements). But in some programming languages, for
example, ALGOL, FORTRAN, BASIC, etc. such a representation is the only
representation to manage a linked list.
Dynamic representation
The efficient way of representing a linked list is using the free pool of storage. In this
method, there is a memory bank (which is nothing but a collection of free memory
spaces) and a memory manager (a program, in fact). During the creation of a linked list,
whenever a node is required the request is placed to the memory manager; the memory
manager will then search the memory bank for the block requested and, if found, grants
the desired block to the caller.
Again, there is also another program called the garbage collector; it plays whenever a
node is no more in use; it returns the unused node to the memory bank.
It may be noted that memory bank is basically a list of memory spaces which is
available to a programmer. Such a memory management is known as dynamic memory
management. The dynamic representation of linked list uses the dynamic memory
management policy.
Then the memory manager will return the pointer of XY to the caller in a temporary
buffer, say NEW. The newly availed node XY then can be inserted at any position in
the linked list by changing the pointers of the concerned nodes. In Figure1, the node
XY is inserted at the end and change of pointers is shown by the dotted arrows. Figure
2 explains the mechanism of how a node can be returned from a linked list to the
memory bank.
Fig1. Allocation of a node from memory bank to a linked list.
Fig2: Returning a node from a linked list to memory bank.
The pointers which are required to be manipulated while returning a node are
shown with dotted arrows. Note that such allocations or deallocations are carried out
by changing the pointers only.
A linked list allocates space for each element separately in its own block of memory called
a "node". The list gets an overall structure by using pointers to connect all its nodes together
like the links in a chain.
Each node contains two fields; a "data" field to store whatever element, and a "next" field
which is a pointer used to link to the next node. Each node is allocated in the heap using
malloc(), so the node memory continues to exist until it is explicitly de-allocated using
free(). The front of the list is a pointer to the “start” node.
A single linked list is shown in figure
The beginning of the linked list is stored in a "start" pointer which points to the first node.
The first node contains a pointer to the second node. The second node contains a pointer to
the third node, ... and so on. The last node in the list has its next field set to NULL to mark
the end of the list. Code can access any node in the list by starting at the start and following
the next pointers.
The start pointer is an ordinary local pointer variable, so it is drawn separately on the left
top to show that it is in the stack. The list nodes are drawn on the right to show that they are
allocated in the heap
• The next field of the new node is made to point the first node (i.e. start node)
in the list by assigning the address of the first node.
• The start pointer is made to point the new node by assigning the address of the
new node.
• Repeat the above steps ‘n’ times.
The following figure shows 4 items in a single linked list stored at different locations in
memory. The function createlist(), is used to create ‘n’ number of nodes:
Insertion of a Node:
One of the most primitive operations that can be done in a singly linked list is the
insertion of a node. Memory is to be allocated for the new node (in a similar way that is
done while creating a list) before reading the data. The new node will contain empty data
field and empty next field. The data field ofthe new node is then stored with the information
read from the user. The next field of the new node is assigned to NULL. The new node can
then be inserted at three different places namely:
1.Inserting a node at the beginning.
2.Inserting a node at the end.
3.Inserting a node at intermediate position.
Inserting a node at the beginning:
The following steps are to be followed to insert a new node at the beginning of the list:
Get the new node using getnode(). newnode = getnode();
If the list is empty then start = newnode.
If the list is not empty, follow the steps given below:
newnode -> next = start; start = newnode;
The following figure shows inserting a node into the single linked list at the beginning.
Store the starting address (which is in start pointer) in temp and prev pointers.
Then traverse the temp pointer upto the specified position followed by prev
pointer.
After reaching the specified position, follow the steps given below: prev -> next
= newnode;
newnode -> next = temp;
The function insert_at_mid(), is used for inserting a node in the intermediate position.
Deletion of a node:
Another primitive operation that can be done in a singly linked list is the deletion of
a node. Memory is to be released for the node to be deleted. A node can be deleted from the
list from three different places namely.
1. Deleting a node at the beginning.
2. Deleting a node at the end.
3. Deleting a node at intermediate position.
Deleting a node at the beginning:
The following steps are followed, to delete a node at the beginning of the list:
If list is empty then display ‘Empty List’ message.
If the list is not empty, follow the steps given below: temp = start;
start = start -> next; free(temp);
Figure shows deleting a node at the beginning of a single linked list.
The function delete_at_beg(), is used for deleting the first node in the list .
Deleting a node at the end:
The following steps are followed to delete a node at the end of the list:
If list is empty then display ‘Empty List’ message.
If the list is not empty, follow the steps given below:
temp = prev = start;
while(temp -> next != NULL)
{
prev=temp;
temp = temp -> next;
}
prev -> next = NULL; free(temp);
Figure shows deleting a node at the end of a single linked list.
The function delete_at_last(), is used for deleting the last node in the list.
Deleting a node at Intermediate position:
The following steps are followed, to delete a node from an intermediate position in the list
(List must contain more than two node).
If list is empty then display ‘Empty List’ message
If the list is not empty, follow the steps given below.
if(pos > 1 && pos < nodectr)
{
temp = prev = start; ctr=1; while(ctr<pos)
{
prev=temp; temp=temp->next; ctr++;
}
prev -> next = temp -> next; free(temp);
printf("\n node deleted..");
}
Figure shows deleting a node at a specified intermediate position other than beginning and
1. Create
2. Insertion
Inserting At Beginning of the list
Inserting At End of the list
Inserting At Specific location in the list
3. Deletion
Deleting from Beginning of the list
Deleting from End of the list
Deleting a Specific Node
4. Display
Here is another more complex function to combine two lists; this one
merges nodes from two sorted lists, preserving their order:
Algorithm
Nodemerge( Node p, Node q ) { if ( p == null)
return q;
else if ( q == null) return p;
else if (p.item < q.item) { p.next
= merge( p.next, q ); return p;
}
else {
q.next = merge( p, q.next ); return q;
}
}
EXAMPLE
Merging is the process of combining two sorted lists into a single sorted list.
4. Continue step 3 until we come across a node that has a next pointer
set to NULL. When we do come across a NULL next pointer we just set the head
node to point to the node that has the NULL next pointer. This node was
previously the tail node, but is now the head node because we are reversing the
linked list.
Algorithm ReverseLinkedlist(struct node **head)
{
struct node *p, *q, *r;
p = q = r = *head; // assign value of head to variable p,q and rp = p->next->next;
// Making p to point third node in the list
q = q->next; // Making q to point second node in the list
r->next = NULL; // Assign pointer field of first node is NULL
q->next = r; // making next value of second node is node first while (p !=
NULL) // as long as p is not NULL
{
r = q; // assign q to r
q = p; // assign p to q
p = p->next; // making p to point the next node in the listq->next = r; //
Making q to point node r
}
*head = q;
}
A double linked list is a two-way list in which all nodes will have two
links. This helps in accessing both successor node and predecessor node from
the given node position. It provides bi-directional traversing. Each node contains
three fields:
• Left link.
• Data.
• Right link.
The left link points to the predecessor node and the right link points to the
successor node. The data field
stores the required data. Many applications require searching forward and
backward thru nodes of a list. For example searching for a name in a telephone
directory would need forward and backward scanning thru a region of the whole
list.
The beginning of the double linked list is stored in a "start" pointer which points
to the first node. The first node’s left link and last node’s right link is set to
NULL.
The following code gives the structure definition:
• The left field of the new node is made to point the previous node.
• The previous nodes right field must be assigned with address of the new node.
locations.
newnode -> right = start; start -> left = newnode; start = newnode;
The function dbl_insert_beg(), is used for inserting a node at the beginning.
Figure shows inserting a node into the double linked list at the beginning.
Inserting a node at the end:
The following steps are followed to insert a new node at the end of the list:
• Get the new node using getnode() newnode=getnode();
• If the list is not empty follow the steps given below: temp = start;
• Ensure that the specified position is in between first node and last node. If
not, specified position is invalid. This is done by countnode() function.
• Store the starting address (which is in start pointer) in temp and prev pointers.
Then traverse the temp pointer upto the specified position followed by prev
pointer.
• After reaching the specified position, follow the steps given below: newnode -
• If the list is not empty, follow the steps given below: temp = start;
It is just a single linked list in which the link field of the last node points
back to the address of the first node. A circular linked list has no beginning
and no end. It is necessary to establish a special pointer called start pointer
always pointing to the first node of the list.
Circular linked lists are frequently used instead of ordinary linked list
because many operations are much easier to implement. In circular linked
list no null pointers are used, hence all pointers contain valid address. A
circular single linked list is shown in figure
The basic operations in a circular single linked list are:
• Creation.
• Insertion.
• Deletion.
• Traversing.
Creating a circular single Linked List with ‘n’ number of nodes:
The following steps are to be followed to create ‘n’ number of nodes:
• Get the new node using getnode(). newnode = getnode();
temp = start;
while(temp -> next != NULL) temp = temp -> next;
temp -> next = newnode;
Repeat the above steps ‘n’ times.
newnode -> next = start;
The function createlist(), is used to create ‘n’ number of nodes:
last = start;
while(last -> next != start) last= last -> next;
newnode -> next = start; start = newnode;
last -> next = start;
The function cll_insert_beg(), is used for inserting a node at the beginning.
Figure shows inserting a node into the circular single linked list at the
beginning.
start = newnode;
newnode -> next = start;
• If the list is not empty follow the steps given below:
temp = start;
while(temp -> next != start) temp = temp -> next;
temp -> next = newnode; newnode -> next = start;
The function cll_insert_end(), is used for inserting a node at the end. Figure
shows inserting a node into the circular single linked list at the end.
Deleting a node at the beginning:
The following steps are followed, to delete a node at the beginning of the list:
• If the list is empty, display a message ‘Empty List’.
list.Figure shows deleting a node at the end of a circular single linked list.