Linear Data Structure 513
Consider the statements
a) if (k==l) pr=first;
b) if (c==k) pr=header;
c) if (c==(k+l)) su=header;
The insertion of node can be done in between two nodes and hence the preceding and succeeding
nodes must be stored in separate pointer variables. When the user specifies 2, the entered value is
reduced by 1 and becomes 1 and is stored in variable k. When value of k is 1, the address of the first
node is stored m the pointer pr. When k is 1, the statement (b) has no reason to consider. The address
of the succeeding node is obtained by the statement (c) and the address obtained is stored in the
pointer variable su. Thus, using following statements proper links are connected.
a) pr->next=nw;
b) nw->next=su;
c) header=first;
Before execution of the above statements, the new node is created using nw pointer, nw is a node to
be inserted.
The address of data field of node nw is linked to the previous node (pr) by the statement
pr - >next=nw.
The address of the succeeding node is stored in the linked field of the new node nw by the statement
nw - >next=su.
Counting Nodes
Sometimes it may be essential to know how many nodes exist in the linked list. The linked list
elements can be counted and displayed. The solution is very easy. In the last few programs
the procedure applied for displaying elements can be applied here. A counter variable can be inserted
there to count the nodes by simply incrementing the counter variable. Consider the following
program.
14.22 Write a program to count the total nodes of the linked list.
# include <stdio.h>
# include <conio.h>
# include <malloc.h>
struct num
{
int num;
struct num *next;
} *h eader,*first,*re ar;
int main ()
{
c lr s c r ();
void form ( vo id);
int count=0;
form ();
printf (" Linked li s t elements are : ");
514 Programming and Data Structures
while (header I-NULL)
r
I
printf (" %d ,header->num);
header-header->next;
count++;
}
printf (" Total Nodes are : %d " , count);
return 0;
void form ( void )
{
struct num *node;
printf (" Enter number : );
i f (header--NULL)
{
first®(struct num*)malloc(sizeof(struct num));
scanf ( "%d" , &first->num);
firs t- >nex t -header;
header*first;
re a r-first;
}
while (1)
{
node*(struct num*) m alloc(sizeof(struct num));
scanf ("%d",&node->num);
if (node->num--0) break;
node->next-NULL;
rear->next-node;
rear-node;
}
}
OUTPUT;
Enter number 123456780
Linked list elements are: 12345678
Total Nodes are: 8
Explanation The above program is the same as the last few programs, the count variable is placed
in the while loop and incremented. The count variable displays the number of nodes.
..................Content has been hidden....................

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