#include
struct thenode
{
struct thenode *prev ;
int data ;
struct thenode * next ;
} ;
void d_append ( struct thenode **, int ) ;
void d_addatbeg ( struct thenode **, int ) ;
void d_addafter ( struct thenode *, int , int ) ;
void d_display ( struct thenode * ) ;
int d_count ( struct thenode * ) ;
void d_delete ( struct thenode **, int ) ;
int main()
{
struct thenode *p ;
p = NULL ;
d_append ( &p , 21 ) ;
d_append ( &p , 2 ) ;
d_append ( &p , 14 ) ;
d_append ( &p , 17 ) ;
d_append ( &p , 99 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements = %d\n", d_count ( p ) ) ;
d_addatbeg ( &p, 33 ) ;
d_addatbeg ( &p, 55 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements = %d\n", d_count ( p ) ) ;
d_addafter ( p, 4, 66 ) ;
d_addafter ( p, 2, 96 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements = %d\n", d_count ( p ) ) ;
d_delete ( &p, 55 ) ;
d_delete ( &p, 2 ) ;
d_delete ( &p, 99 ) ;
d_display ( p ) ;
printf ( "\nNo. of elements = %d\n", d_count ( p ) ) ;
}
void d_append ( struct thenode **s, int num )
{
struct thenode *r, *q = *s ;
if ( *s == '\0' )
{
fflush(stdin);
*s = ( struct thenode* ) malloc ( sizeof ( struct thenode ) ) ;
( *s ) -> prev = NULL ;
( *s ) -> data = num ;
( *s ) -> next = NULL ;
}
else
{
while ( q -> next != NULL )
q = q -> next ;
r = (struct thenode* ) malloc ( sizeof ( struct thenode ) ) ;
r -> data = num ;
r -> next = NULL ;
r -> prev = q ;
q -> next = r ;
}
}
void d_addatbeg ( struct thenode **s, int num )
{
struct thenode *q ;
q = ( struct thenode* ) malloc ( sizeof ( struct thenode ) ) ;
q -> prev = NULL ;
q -> data = num ;
q -> next = *s ;
( *s ) -> prev = q ;
*s = q ;
}
void d_addafter ( struct thenode *q, int loc, int num )
{
struct thenode *temp ;
int i ;
for ( i = 0 ; i < loc ; i++ )
{
q = q -> next ;
if ( q == NULL )
{
printf ( "\nThere are less than %d elements", loc );
return ;
}
}
q = q -> prev ;
temp = ( struct thenode* ) malloc ( sizeof ( struct thenode ) ) ;
temp -> data = num ;
temp -> prev = q ;
temp -> next = q -> next ;
temp -> next -> prev = temp ;
q -> next = temp ;
}
void d_display ( struct thenode *q )
{
printf ( "\n" ) ;
while ( q != NULL )
{
printf ( "%2d\t", q -> data ) ;
q = q -> next ;
}
}
int d_count ( struct thenode * q )
{
int c = 0 ;
while ( q != NULL )
{
q = q -> next ;
c++ ;
}
return c ;
}
void d_delete ( struct thenode **s, int num )
{
struct thenode *q = *s ;
while ( q != NULL )
{
if ( q -> data == num )
{
if ( q == *s )
{
*s = ( *s ) -> next ;
( *s ) -> prev = NULL ;
}
else
{
if ( q -> next == NULL )
q -> prev -> next = NULL ;
else
{
q -> prev -> next = q -> next ;
q -> next -> prev = q -> prev ;
}
free ( q ) ;
}
return ;
}
q = q -> next ; /* go to next node */
}
printf ( "\n%d not found.", num ) ;
return;
}
Output:
21 2 14 17 99
No. of elements = 5
55 33 11 2 14 17 99
No. of elements = 7
55 33 96 11 2 66 14 17 99
No. of elements = 9
33 96 11 66 14 17
No. of elements = 6
No comments:
Post a Comment