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

Unit - II Lecture Slides

Uploaded by

Saibabu maredhu
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)
10 views

Unit - II Lecture Slides

Uploaded by

Saibabu maredhu
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/ 109

Unit - II

Linked lists
Unit – II Syllabus

• Single linked list,


• double linked list,
• circular linked list,
• operations on linked lists.
Introduction

Let us consider the list of elements 20, 33, 14, 65, 81 needs to store in memory

Array representation

--- ---- --- 20 33 14 65 81 -----


100 101 102 103 104 105 106 107 108 109 110 111 112 113

100
102
104
106
108
Linked list processing
Linked list
• 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.
The disadvantages of arrays are:
• The size of the array is fixed. Most often this size is specified at
compile time. This makes the programmers to allocate arrays, which
seems "large enough" than required.
• Inserting new elements at the front is potentially expensive because
existing elements need to be shifted over to make room.
• Deleting an element from an array is not possible
Note: Binary searching is not possible on linked list representation
Linked List is a linear data structure,

• A linear data structure is one where data items are arranged in a


linear fashion. Each member is attached to its neighboring elements.
• The structure permits single-level data storage because the data
elements are stored in a linear fashion. The data can be traversed in
one run.
• A linear data structure does not maximize memory.
• The complexity of the structure's time increases with an increase in
Most Common Operations Performed in Linear Data
TraversalStructures
A traversal operation is used to visit every data structure node in a particular order. This is a
technique that can be used to print, search, display, and read data stored in a structure.
2. Insertion
Insertion operations add data elements to a database structure. This can be operated at any point in
the data structure, including its beginning, middle, and end.
3. Deletion
Data elements are removed from a data structure by deletion operations. These operations are
usually performed on nodes that no longer need them.
4. Search Operation
Search operations can be used to locate a particular data element within a data structure. These
operations often use a compare function in order to determine if two elements are equal.
5. Sort Operation
Sort operations are used for arranging data elements in a data structure in a particular order. You
can use a variety of sorting algorithms to accomplish this, including bubble sort, insertion sorts.

6. Traversing: Visiting the each and every element in list.


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.
Start
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the
execution of a program.
2. Linked lists have efficient memory utilization. Here, memory is not preallocated.
Memory is allocated whenever it is required and it is de-allocated (removed) when
it is no longer needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in
inserting a data item at a specified position and deletion of the data item from the
given position.
4. Many complex applications can be easily carried out with linked lists.

Disadvantages of linked lists:


5. It consumes more space because every node requires a additional pointer to store
address of the next node.
6. 2. Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:

1. Single 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.

2. Double 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.

3. Circular Linked List: 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.
4. Circular Double Linked List: A circular double linked list is one, which has both the successor pointer
and predecessor pointer in the circular manner.
Applications of Linked Lists

1. Linked lists are used to represent and manipulate polynomial. Polynomials are
expression containing terms with non zero coefficient and exponents. For
example: P(x) = a0 Xn + a1 Xn-1 + …… + an-1 X + an

2. Represent very large numbers and operations of the large number such as
addition, multiplication and division.

3. Linked lists are to implement stack, queue, trees and graphs.

4. Implement the symbol table in compiler construction


Review on pointers concept:

• malloc() is a system function which allocates a block of memory in the


"heap" and returns a pointer to the new block.
• The prototype of malloc() and other heap functions are in stdlib.h.
• malloc() returns NULL if it cannot fulfill the request.
• It is defined by:
void *malloc (number_of_bytes)
Since a void * is returned the C standard states that this pointer can be
converted to any type.
For example,
char *cp;
cp = (char *) malloc (100);
Attempts to get 100 bytes and assigns the starting address to cp.
We can also use the sizeof() function to specify the number of bytes.
For example, int *ip; ip = (int *) malloc (100*sizeof(int));
free() is the opposite of malloc(), which de-allocates memory.
The argument to free() is a pointer to a block of memory in the heap — a
pointer which was obtained by a malloc() function. T
he syntax is:
free (ptr);

The advantage of free() is simply memory management when we no longer


need a block.
Single linked list
• 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.
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.
Implementation of Single Linked List: Node declaration

Before writing the code to build the list, we need to create a start node, used to create and access other
nodes in the linked list.
• Creating a structure with one data item and a next pointer, which will be pointing to next node of the list.
This is called as self-referential structure.
• Initialize the start pointer to be NULL.
The basic operations in a single linked list are:
• Creation.
• Insertion.
• Deletion.
• Traversing.
Creating a node for Single Linked List:

Creating a singly linked list starts with creating a node.


Sufficient memory has to be allocated for creating a node. The information is stored in
the memory, allocated by using the malloc() function.
The function getnode(), is used for creating a node, after allocating memory for the
structure of type node, the information for the item (i.e., data) has to be read from the
user, set next field to NULL and finally returns the address of the node.
The creation of a node for single linked list as illustrated below:.
Creating a Singly 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();
• If the list is empty, assign new node as start.
start = newnode;
• If the list is not empty, follow the steps given below:

• 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.
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 of
the 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:

• Inserting a node at the beginning.


• Inserting a node at the end.
• Inserting a node at intermediate position
1. 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(); void insert_at_beg()
• If the list is empty then {
start = newnode. node *newnode;
newnode = getnode();
• If the list is not empty, follow the steps given below: if(start == NULL)
newnode -> next = start; {
start = newnode; start = newnode;
}
else
{
newnode -> next = start;
start = newnode;
}
}
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 empty then
start = newnode.
• If the list is not empty follow the steps given below:
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
Inserting a node at intermediate position:
The following steps are followed, to insert a new node in an intermediate position in the
list:
• Get the new node using getnode().
newnode = getnode();
• 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:
prev -> next = newnode;
newnode -> next = temp;
• Let the intermediate position be 3.
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.

• Deleting a node at the beginning.


• Deleting a node at the end.
• 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);
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);
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..");
}
Traversal and displaying a list (Left to Right):

To display the information, you have to traverse (move) a linked list, node by node from the first node,
until the end of the list is reached.
Traversing a list involves the following steps:

• Assign the address of start pointer to a temp pointer.


• Display the information from the data field of each node.
The function traverse() is used for traversing and displaying the information stored in the list from left to
right.
The function rev_traverse(), is used for traversing and displaying the information stored in the list from right
to left.
Source Code for the Implementation of Single Linked List:
Single linked list Using a header node

A header node is a special dummy node found at the front of the list.
The use of header node is an alternative to remove the first node in a list.
For example, the picture below shows how the list with data 10, 20 and 30 would be represented using a linked list
without and with a header node:

header
Note that if you do decide to use a header node, you must remember to initialize an empty list to
contain one (dummy) node, you must remember not to include the header node in the count of "real"
nodes in the list.

It is also useful when information other than that found in each node of the list is needed.

For example, imagine an application in which the number of items in a list is often calculated.
In a standard linked list, the list function to count the number of nodes has to traverse the entire list every time.
However, if the current length is maintained in a header node, that information can be obtained very quickly.
Array based linked lists:
Another alternative is to allocate the nodes in blocks.
In fact, if you know the maximum size of a list a head of time, you can pre-allocate the nodes in a single array.
The result is a hybrid structure – an array based linked list.
Figure below shows an example of null terminated single linked list where all the nodes are allocated
contiguously in an array.
Circular Singly Linked List

• In a circular Singly linked list, the last node of the list contains a
pointer to the first node of the list. We can have circular singly linked
list as well as circular doubly linked list.
• We traverse a circular singly linked list until we reach the same node
where we started. The circular singly liked list has no beginning and
no ending. There is no null value present in the next part of any of the
nodes.

Circular linked list are mostly used in task maintenance in operating systems.
There are many examples where circular linked list are being used in computer science
including browser surfing where a record of pages visited in the past by the user, is
maintained in the form of circular linked lists and can be accessed again on clicking the
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();
• If the list is empty, assign new node as start.
start = newnode;
• If the list is not empty, follow the steps given below:
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
Inserting a node at the beginning:

The following steps are to be followed to insert a new node at


the beginning of the circular list:

• Get the new node using getnode().


newnode = getnode();
• If the list is empty, assign new node as start.
start = newnode; newnode -> next = start;
• If the list is not empty, follow the steps given below:
last = start;
while(last -> next != start)
last = last -> next;
newnode -> next = start;
start = newnode;
last -> next = start;
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 empty, assign new node as start.
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;
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’.
• If the list is not empty, follow the steps given below:
last = temp = start;
while(last -> next != start)
last = last -> next;
start = start -> next;
last -> next = start;
• After deleting the node, if the list is empty then start = NULL.
Deleting a node at the end:
The following steps are followed to delete a node at the end of the
list:
• If the list is empty, display a message ‘Empty List’.
• If the list is not empty, follow the steps given below:
temp = start;
prev = start;
while(temp -> next != start)
{
prev = temp;
temp = temp -> next;
}
prev -> next = start;
• After deleting the node, if the list is empty then start = NULL
Traversing a circular single linked list from left to right:

The following steps are followed, to traverse a list from left


to right:
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start;
do {
printf("%d ", temp -> data);
temp = temp -> next;
} while(temp != start);
Source Code for Circular Single Linked List:
Double Linked List:

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 basic operations in a double linked list are:

• Creation.
• Insertion.
• Deletion.
• Traversing
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.
Creating a node for Double Linked List:

Creating a double linked list starts with creating a node.


Sufficient memory has to be allocated for creating a node.
The information is stored in the memory, allocated by using the malloc() function.
The function getnode(), is used for creating a node, after allocating memory for the
structure of type node, the information for the item (i.e., data) has to be read from
the user and set left field to NULL and right field also set to NULL.
Creating a Double 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();
• If the list is empty then start = newnode.
• If the list is not empty, follow the steps given below:

• 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.
• Repeat the above steps ‘n’ times.

The function createlist(), is used to create ‘n’ number of nodes:


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 -> right = start;
start -> left = newnode;
start = newnode;
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 empty then start = newnode.
• If the list is not empty follow the steps given below:
temp = start;
while(temp -> right != NULL)
temp = temp -> right;
temp -> right = newnode;
newnode -> left = temp;
The function dbl_insert_end(), is used for inserting a node at the end.
Inserting a node at an intermediate position:

The following steps are followed, to insert a new node in an intermediate position in
the list:

• Get the new node using getnode(). newnode=getnode();


• 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 -> left = temp;
newnode -> right = temp -> right;
temp -> right -> left = newnode;
temp -> right = newnode;
The function dbl_insert_mid(), is used for inserting a node in the intermediate
position.
Inserting a node at an 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 -> right;
start -> left = NULL;
free(temp);
The function dbl_delete_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 = start;
while(temp -> right != NULL)
{
temp = temp -> right;
}
temp -> left -> right = NULL;
free(temp);
The function dbl_delete_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 nodes).
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
• Get the position of the node to delete.
• Ensure that the specified position is in between first node and last node. If not, specified position is invalid.
Then perform the following steps:
if(pos > 1 && pos < nodectr)
{
temp = start;
i = 1;
while(i < pos)
{
temp = temp -> right;
i++;
}
temp -> right -> left = temp -> left;
temp -> left -> right = temp -> right;
free(temp);
printf("\n node deleted..");
}
The function delete_at_mid(), is used for deleting the intermediate node in the list
Traversal and displaying a list (Right to Left):

To display the information from right to left, you have to traverse the list, node by node
from the first node, until the end of the list is reached.
The function traverse_right_left() is used for traversing and displaying the information
stored in the list from right to left.
The following steps are followed, to traverse a list from right to left:
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start;
while(temp -> right != NULL)
temp = temp -> right;
while(temp != NULL)
{
print temp -> data;
temp = temp -> left;
}
Counting the Number of Nodes:
The following code will count the number of nodes exist in the list (using recursion).
A Complete Source Code for the Implementation of Double Linked List
Circular double Linked List
• Circular doubly linked list is a more complexed type of data structure
in which a node contain pointers to its previous node as well as the
next node.
• Circular doubly linked list doesn't contain NULL in any of the node.
• The last node of the list contains the address of the first node of the
list.
• The first node of the list also contain address of the last node in its
previous pointer.
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.
The basic operations in a
circular single linked list are:
• Creation.
• Insertion.
• Deletion.
• Traversing.
Creating a Circular Double 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();
• If the list is empty, then do the following start = newnode;
newnode -> left = start; newnode ->right = start;
• If the list is not empty, follow the steps given below:
newnode -> left = start -> left;
newnode -> right = start;
start -> left->right = newnode;
start -> left = newnode;
• Repeat the above steps ‘n’ times.
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;
newnode -> left = start;
newnode -> right = start;
• If the list is not empty, follow the steps given below:
newnode -> left = start -> left;
newnode -> right = start;
start -> left -> right = newnode;
start -> left = newnode;
start = newnode;
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 empty, then start = newnode;
newnode -> left = start;
newnode -> right = start;
• If the list is not empty follow the steps given below:
newnode -> left = start -> left;
newnode -> right = start;
start -> left -> right = newnode;
start -> left = newnode;
Inserting a node at an intermediate position:

The following steps are followed, to insert a new node in an intermediate


position in the list:
• Get the new node using getnode().
newnode=getnode();
• 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. Then traverse the
temp pointer upto the specified position.
• After reaching the specified position, follow the steps given below:
newnode -> left = temp;
newnode -> right = temp -> right;
temp -> right -> left = newnode;
temp -> right = newnode;
nodectr++;
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 -> right;
temp -> left -> right = start;
start -> left = temp -> left;
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 = start;
while(temp -> right != start)
{
temp = temp -> right;
}
temp -> left -> right = temp -> right;
temp -> right -> left = temp -> left;
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:
• Get the position of the node to delete.
• Ensure that the specified position is in between first node and last node. If not, specified position
is invalid.
• Then perform the following steps:
if(pos > 1 && pos < nodectr)
{
temp = start;
i = 1;
while(i < pos)
{
temp = temp -> right ;
i++;
}
temp -> right -> left = temp -> left;
temp -> left -> right = temp -> right;
free(temp);
printf("\n node deleted..");
nodectr--;
}
Traversing a circular double linked list from left to right:

The following steps are followed, to traverse a list from left to right:
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start;
Print temp -> data;
temp = temp -> right;
while(temp != start)
{
print temp -> data;
temp = temp -> right;
}
Traversing a circular double linked list from right to left:

The following steps are followed, to traverse a list from right to


left:
• If list is empty then display ‘Empty List’ message.
• If the list is not empty, follow the steps given below:
temp = start;
do
{
temp = temp -> left;
print temp -> data;
} while(temp != start);
Source Code for Circular Double Linked List:
# include int menu()
# include {
# include int ch;
struct cdlinklist clrscr();
{ printf("\n 1. Create "); printf("\n\n--------------------------");
struct cdlinklist *left; printf("\n 2. Insert a node at Beginning");
int data; printf("\n 3. Insert a node at End");
struct cdlinklist *right; printf("\n 4. Insert a node at Middle"); printf("\n\n--------------------------");
}; printf("\n 5. Delete a node from Beginning"); printf("\n 6. Delete a node from End");
typedef struct cdlinklist node; printf("\n 7. Delete a node from Middle"); printf("\n\n--------------------------");
node *start = NULL; printf("\n 8. Display the list from Left to Right");
int nodectr; printf("\n 9. Display the list from Right to Left");
node* getnode() printf("\n 10.Exit"); printf("\n\n Enter your choice: ");
{ scanf("%d", &ch); return ch;
node * newnode; }
newnode = (node *) malloc(sizeof(node));
printf("\n Enter data: ");
scanf("%d", &newnode -> data);
newnode -> left = NULL;
newnode -> right = NULL;
return newnode;
}
void cdll_createlist(int n)
{ int i;
node *newnode, *temp;
if(start == NULL)
{
nodectr = n;
for(i = 0; i < n; i++)
{ newnode = getnode();
if(start == NULL)
{
start = newnode;
newnode -> left = start;
newnode ->right = start;
}
else
{
newnode -> left = start -> left;
newnode -> right = start;
start -> left->right = newnode;
start -> left = newnode; } } }
else
printf("\n List already exists..");}
void cdll_display_left_right() void cdll_display_right_left()
{ {
node *temp; node *temp;
temp = start; temp = start;
if(start == NULL) if(start == NULL)
printf("\n Empty List"); printf("\n Empty List");
else else
{ {
printf("\n The contents of List: "); printf("\n The contents of List: ");
printf(" %d ", temp -> data); do
temp = temp -> right; {
while(temp != start) temp = temp -> left;
{ printf("\t%d", temp -> data);
printf(" %d ", temp -> data); } while(temp != start);
temp = temp -> right; }
} }
}
}
void cdll_insert_end()
void cdll_insert_beg()
{
{
node *newnode,*temp;
node *newnode;
newnode = getnode();
newnode = getnode();
nodectr++;
nodectr++;
if(start == NULL)
if(start == NULL)
{
{
start = newnode;
start = newnode;
newnode -> left = start;
newnode -> left = start;
newnode -> right = start;
newnode -> right = start;
}
}
else
else
{
{
newnode -> left = start -> left;
newnode -> left = start -> left;
newnode -> right = start;
newnode -> right = start;
start -> left -> right = newnode;
start -> left -> right = newnode;
start -> left = newnode;
start -> left = newnode;
}
start = newnode; } }
void cdll_insert_mid()
if(pos > 1 && pos <= nodectr)
{
{
node *newnode, *temp, *prev;
temp = start;
int pos, ctr = 1;
while(ctr < pos - 1)
newnode = getnode();
{
printf("\n Enter the position: ");
temp = temp -> right;
scanf("%d", &pos);
ctr++;
if(pos - nodectr >= 2)
}
{
newnode -> left = temp;
printf("\n Position is out of range..");
newnode -> right = temp -> right;
return;
temp -> right -> left = newnode;
}
temp -> right = newnode;
nodectr++;
printf("\n Node Inserted at Middle.. ");
}
else printf("position %d of list is not a middle
position", pos); } }
void cdll_delete_beg()
{ else
node *temp; {
if(start == NULL) temp = start;
{ start = start -> right;
printf("\n No nodes exist.."); temp -> left -> right = start;
getch(); start -> left = temp -> left;
return ; free(temp);
} }
else printf("\n Node deleted at Beginning..");
{ }
nodectr--; }
if(nodectr == 0)
{
free(start);
start = NULL;
}
void cdll_delete_last() else
{ {
node *temp; temp = start;
if(start == NULL) while(temp -> right != start)
{ temp = temp -> right;
printf("\n No nodes exist.."); getch(); temp -> left -> right = temp -> right;
return; temp -> right -> left = temp -> left;
} free(temp);
else }
{ printf("\n Node deleted from end ");
nodectr--; }
if(nodectr == 0) }
{
free(start);
start = NULL;
}
void cdll_delete_mid() if(pos > 1 && pos < nodectr)
{ int ctr = 1, pos; {
node *temp; temp = start;
if( start == NULL) while(ctr < pos)
{ {
printf("\n No nodes exist.."); temp = temp -> right ;
getch(); ctr++;
return; }
} temp -> right -> left = temp -> left;
Else temp -> left -> right = temp -> right;
{ free(temp);
printf("\n Which node to delete: "); printf("\n node deleted..");
scanf("%d", &pos); nodectr--;
if(pos > nodectr) }
{ else
printf("\nThis node does not {
exist"); getch(); printf("\n It is not a middle position..")
return; }
Void main(void)
{ int ch,n;
clrscr();
while(1)
{ case 5 : cdll_delete_beg();
ch = menu(); break;
switch( ch) case 6 : cdll_delete_last();
{ break;
case 1 : printf("\n Enter Number of nodes to create: "); case 7 : cdll_delete_mid();
scanf("%d", &n); break;
cdll_createlist(n); case 8 : cdll_display_left_right();
printf("\n List created.."); break;
break; case 9 : cdll_display_right_left();
case 2 : cdll_insert_beg(); break;
break; case 10: exit(0);
case 3 : cdll_insert_end(); }
break; getch(); } }
case 4 : cdll_insert_mid();
• The major disadvantage of doubly linked lists (over singly linked lists) is
that they require more space (every node has two pointer fields instead
of one).
• Also, the code to manipulate doubly linked lists needs to maintain the
prev fields as well as the next fields;
• the more fields that have to be maintained, the more chance there is for
errors.
• The major advantage of doubly linked lists is that they make some
operations (like the removal of a given node, or a right-to-left traversal of
the list) more efficient.
• The major advantage of circular lists (over non-circular lists) is that they
eliminate some extra-case code for some operations (like deleting last
node).
• Also, some applications lead naturally to circular list representations. For
example, a computer network might best be modeled using a circular list.
Applications pf Linked lists
Source code for polynomial creation with help of linked list:
Addition of Polynomials:

To add two polynomials we need to scan them once. If we find terms


with the same exponent in the two polynomials, then we add the
coefficients; otherwise, we copy the term of larger exponent into the
sum and go on.
When we reach at the end of one of the polynomial, then remaining part
of the other is copied into the sum.
To add two polynomials follow the following steps:
• Read two polynomials.
• Add them.
• Display the resultant polynomial.
Practice Programs on linked lists:
1. Write a “C” functions to split a given list of integers represented by a single linked list into two lists in the
following way. Let the list be L = (l0, l1, ….., ln). The resultant lists would be R1 = (l0, l2, l4, …..) and R2 = (l1, l3,
l5, …..).
2. Suppose that an ordered list L = (l0, l1, …..,ln) is represented by a single linked list. It is required to append the
list L = (ln, l0, l1, ….., ln) after another ordered list M represented by a single linked list
3. Write a “C” function to concatenate two circular linked lists producing another circular linked list.
4. Write “C” functions to compute the following operations on polynomials represented as singly connected
linked list of nonzero terms. 1. Evaluation of a polynomial
2. Multiplication of two polynomials.
5. Write a “C” function to represent a sparse matrix having “m” rows and “n” columns using linked list.
6. Write a “C” function to print a sparse matrix, each row in one line of output and properly formatted, with zero
being printed in place of zero elements.
7. Write “C” functions to:
1. Add two m X n sparse matrices and
2. Multiply two m X n sparse matrices.
Where all sparse matrices are to be represented by linked lists.

You might also like