Linear Data Structure 525
Insertion at the end or a specified position: An element can be inserted at a specific position in
the linked list. The following program code can be inserted in the previous program. The following
function can be used to insert an element at a specified position.
int addafter(int n, int p )
{
struct doubly *teinp,*t;
int j;
t -f ir s t ;
for (j«0 ;j< p -l;j+ + )
{
t«t->n*xt;
i f (t NULL)
{
printf ("n There are less than %d elements : "#p);
return 0;
}
}
temp*(struct doubly*)malloc( sizeof(struct doubly));
temp->next■t->nexti
temp->number«n;
t->next*temp;
return 0;
>
Explanation The above function can be used to insert an element at a specified position. The
user has to enter the element and position where the element is to be inserted. Using for loop the
specified location is searched. Using m alloc () function, a new node is created. The next pointer
is assigned an address of the next node and previous (p) pointer is assigned the address of the
previous node. Thus, the node is successfully inserted at the specified position. Using the same
function the element at the end can be inserted.
Deletion
An element can be removed from the linked list by an operation called deletion. Deletion can be
done at the beginning or at a specified position.
Header
5 41
Node 1
& 8 &
Node 2
& 9
X
Node 3
Node to be deleted
(a) Before deletion
526 Programming and Data Structures
(b) After deletion
Fig. 14.25 Deletion from the linked list
In the deletion process the memory of the node to be deleted is released using free (
The previous and next nodes are linked.
ram (int d)
{
struct doubly *temp,*l;
i f (first->number*=d)
{
temp»first;
first «first ->n e x t;
free(temp);
return 0;
}
l-fire t?
while (l->next->next!-NULL)
{
i f (1->next->number«»d)
{
temp«l->next;
1->next*temp->next;
free(temp);
return 0;
}
l-l-> next;
}
i f (1 - >next->number*od)
{
tomp*l->next;
free(temp);
1 - >next oNXJLL;
return 0;
}
printf ("%d not foundn",d);
getchO ;
) function.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.34.39