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

#3414
Humayan
Participant

Heres some code I found on my hard drive :
 

#include
//simple list
struct node
{
 int i;
 node * next;
};
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;
 int i;
 do
 {
  cout << "choose an operation: " << endl;
  cout << "1. add a node to back of list" << endl;
  cout << "2. add a node to front of list" << endl;
  cout << "3. print the list. " << endl;
  cout << "4. exit " << endl;
  cin >> choice;
  cin.get();
  cout << endl;
  switch ( choice )
  {
   case '1':
   {
    cout << " enter an integer : " ;
    cin >> i;
    addBack ( i , head , tail );
   };
   break;
   case '2':
   {
    cout << " enter an integer : " ;
    cin >> i;
    addFront ( i , head , tail );
   };
   break;
   case '3':
   {
    print ( head );
   };
   break;
   case '4':
   {
    cout <<"goodbye!" << endl;
   };
   break;
   default: cout << "bad choice !" << endl;
  
  };
  cout << endl;
 }
 while ( choice != '4' );
 destroy ( head ); 
 
 
}
void print ( node * r )
{
 node * t = r;
 cout << "This is the list: " << endl;
 
 while ( t != NULL )
 {
  cout << " " << t -> i << " ";
  t = t -> next;
 }
 cout << endl;
}
void addBack ( int n , node *& h  , node *& t )
{
 if ( h == NULL )
 {
  h = t = new node;
  t -> i = n;
  t -> next = NULL;
 }
 else
 {
  
  t -> next = new 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 = new node;
  t -> i = n;
  t -> next = NULL;
 }
 else //add to front
 {
  node * temp = h;
  
  h = new node;
  h -> i = n;
  h -> next = temp;
 }
}
void destroy ( node *& h )
{
 node * temp;
 while ( h != NULL )
 {
  temp = h;
  h = h -> next;
  delete temp;
 }
}