Home Forums C Programming Can You Help Me Plz! Reply To: Can You Help Me Plz!

#3415
Humayan
Participant

Heres a quick translation into c:
 

#include < stdlib.h >
#include < stdio.h >
//simple list
typedef struct nodeType
{
 int i;
 struct nodeType * next;
} node;
void print ( node * );
void addBack ( int , node **  , node ** );
void addFront ( int , node ** , node ** );
void destroy ( node ** );
void main()
{
 node * head = NULL;
 node * tail = NULL;
 char choice;
 char newline;
 int i;
 do
 {
  printf ( "choose an operation: n" );
  printf ( "1. add a node to back of list n" );
  printf ( "2. add a node to front of list n" );
  printf ( "3. print the list. n" );
  printf ( "4. exit n" );
  choice = getchar ();
  newline = getchar ();
  printf ( "n" );
  switch ( choice )
  {
   case '1':
   {
    printf ( "enter an integer : n" );
    scanf ( "%d",& i );
    addBack ( i , & head , & tail );
    newline = getchar ();
   };
   break;
   case '2':
   {
    printf ( "enter an integer : n" );
    scanf ( "%d",& i );
    addFront ( i , & head , & tail );
    newline = getchar ();
   };
   break;
   case '3':
   {
    print ( head );
   };
   break;
   case '4':
   {
    printf ( "goodbye! n" );
   };
   break;
   default: printf ( "bad choice ! n" );
  
  };
  printf ( "n" );
 }
 while ( choice != '4' );
 destroy ( & head ); 
 
 
}
void print ( node * r )
{
 node * t = r;
 printf ( "This is the list: n" );
 
 while ( t != NULL )
 {
  printf ( "%c" ," " );
  printf ( "%i" , t -> i );
  printf ( "%c" , " " );
  t = t -> next;
 }
 printf ( "n" );
}
void addBack ( int n , node ** h  , node ** t )
{
 if ( ( * h  ) == NULL )
 {
  ( * h ) = ( * t ) = malloc ( sizeof ( node ) );
  ( * t ) -> i = n;
  ( * t ) -> next = NULL;
 }
 else
 {
  
  ( * t ) -> next = malloc ( sizeof ( node ) );
  ( * t ) -> next -> i = n;
  ( * t ) -> next -> next = NULL;
  ( * t ) = ( * t ) -> next;
 
 }
}
void addFront ( int n , node ** h , node ** t )
{
 if ( ( * h ) == NULL ) //empty list
 {
  
  ( * h ) = ( * t ) = malloc ( sizeof ( node ) );
  ( * t ) -> i = n;
  ( * t ) -> next = NULL;
 }
 else //add to front
 {
  node * temp = ( * h );
  
  ( * h ) = malloc ( sizeof ( node ) );
  ( * h ) -> i = n;
  ( * h ) -> next = temp;
 }
}
void destroy ( node ** h )
{
 node * temp;
 while ( ( * h ) != NULL )
 {
  temp = ( * h );
  ( * h ) = ( * h ) -> next;
  free ( temp );
 }
}