#include<iostream>
using namespace std;
struct Node
{
  int data;
  Node *next;      
};

Node *first,*now,*ptr,*pre;

int show()
{
  int ans;
  cout<<"1. Insert \n";
  cout<<"2. Delete \n";
  cout<<"3. Print  \n";
  cout<<"Your select ==>  ";
  cin>>ans;
  return ans;    
}            

void Insert(int DATA)
{
  now=new Node; 
  now->data=DATA;  
  if(first==NULL)          
   {
    first=now;
    now->next=NULL;
   }                               
  else if( first->data > DATA )
       {    
          now->next=first;
          first=now;
       }
       else 
       {
         ptr=first;                              
         while( ptr ) 
         {        
             if(ptr->data < DATA)
              { pre=ptr;  ptr=ptr->next;  }
             else
               break; 
         }
         now->next=ptr; 
         pre->next=now;
       }
}

void Delete(int DATA)
{
  if(first==NULL)          
    cout<<"無資料可刪除\n";
  else if(first->data == DATA)
          {
            ptr=first;
            first=first->next;
            delete ptr;                     
          }
       else
        {
          ptr=first;
          while(ptr)
            {
             if(ptr->data==DATA)
               { pre->next=ptr->next; delete ptr; break; }
             else
               { pre=ptr; ptr=ptr->next; }     
            }
          if(ptr==NULL )
              cout<<"查無此資料可供刪除\n";
        }                               
}

void Print()
{
  ptr=first;
  if(ptr==NULL)          
     cout<<"無資料可供列印\n";
  else
    while(ptr)
     {
       cout<<ptr->data<<"  ";
       ptr=ptr->next;
     }  
     
  cout<<"\n";   
}

int main()
{
  first=NULL;  
  int k;
  while(1)
  {
    switch( show() )
    {
      case 1:
           cout<<"Data ==> ";
           cin>>k;
           Insert(k);
           break;
      case 2:
           cout<<"Delete Data ==> ";
           cin>>k;          
           Delete(k); 
           break;
      case 3:      
           Print();
           break;             
            
    }            
          
          
  }          

  system("pause");
  return 0;
}
