Thread: Same Questiion But I Do Not Know How To Do It In Linked List.

  1. #16
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    here is the same progrm just more efficient(works fine).please explain where and how to modify it to linked lists.


    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
            /**************************************************************/
                    /*Declaration of a Structure of Type PART*/ 
    typedef struct {
            int    ID;
            char   desc[50];
            int    quant;
            float  price;
            
            }PART;
            /*************************************************************/
    PART part[1000];
    int count=0;
    int parts_sold=0;
    float total=0;
    FILE*in;
    /******************************************************************************/
                            /*Declaration of Functions*/
    void insertinorder(int);
    void getdescription(char[]); 
    void addnewpart();
    void changeprice();
    void addquant();
    void sellpart();
    void printparts();
    int  binarysearch(int);
    /******************************************************************************/
    /*
       The Main Function Opens the file "parts.dat" and reads the required data
       And assigns the data to the Structure based on its Field.
       It Then Calls The Various Funtions Based On The "Code" Received.
    */
    
    int main () 
    {    
        int tempid,execute=1;
        char word[100],ch;
        char chs[3];    
        
        in=fopen("parts.dat","r");
        if (in==NULL){
                      printf("Error!!!File \"parts.dat\" Not Found\n");
                      system("pause");
                      return 1;
                     } 
        
        fscanf(in,"&#37;d",&tempid);
        while(tempid!=0)
             {
                    insertinorder(tempid);
                    count++;
                    fscanf(in,"%d",&tempid);
             }      
                
          while (execute==1)      
        {                     
            ch=getc(in);
            while (ch == ' ') 
                  ch=getc(in);
                  
            chs[0]=getc(in);
            
            if (chs[0] != EOF) 
            {
               chs[1]=getc(in);
               chs[2]='\0';
               
               if (strcmp(chs,"ap")==0)
                   addnewpart();
            
          else if (strcmp(chs,"sp")==0)          
                   sellpart();   
                   
          else if (strcmp(chs,"cp")==0)          
                   changeprice();    
        
          else if (strcmp(chs,"cq")==0)           
                   addquant();
                   
          else if (strcmp(chs,"ls")==0)            
                   printparts();
            }
          else
              execute=0;   
        } 
             
         printf("\nThe Total Number Of Parts Sold Was:%d\n",parts_sold);
         printf("The Total Sales Amounted to:$%5.2f\n",total);
             
                 printf("\n");
                 fclose(in);
                 system("pause");
                 return 0;
                 
    }
    /******************************************************************************/
    /*
        The Following Function Is Responsible For Inserting A Part In Order.
    */
    void insertinorder(int tempid)
    {
         int k=count-1;
         while (k>=0 && tempid<part[k].ID){
               part[k+1]=part[k];
               k--;
               }
         part[k+1].ID=tempid;
         getdescription(part[k+1].desc);
         fscanf(in,"%d",&part[k+1].quant);
         fscanf(in,"%f",&part[k+1].price);
    }     
    /******************************************************************************/
    /*
        The Following Function Is Responsible For Capturing The Description
        Whilst Rejecting The Character "*" Between Which The Description Is 
        Encased.
    */
    void getdescription(char word[])
    {
         char c;
         int n=0;
         
         while ((c=getc(in))== ' ' && c!='*') ;
         c=getc(in);
         word[n]=c;
         
         while ((c=getc(in))!='*') 
         {
               n++;
               word[n]=c;
         }
         word[++n]='\0';
    }     
    
    /******************************************************************************/
    /*
        The Following Function Adds A New Part To The List Of Existing Parts
        In Order.
    */
    void addnewpart()
    {
         int tempid;
         fscanf(in,"%d",&tempid);
         insertinorder(tempid);
         count++;
    }
    /*****************************************************************************/
    /*  
      The Following Function Updates The Price Field Of A Part
    */
    void changeprice()
    {
         int id,ID;
         float newprice;
         fscanf(in,"%d",&id);
         fscanf(in,"%f",&newprice);
         ID=binarysearch(id);
            if (ID==-1)
            printf("\nThe Part %d Price Cannot Be Altered. Part Entry Not Found!\n",id);
         else  
            {
             part[ID].price=newprice;    
            }
    }
    /*****************************************************************************/
    /*  
        The Following Function Updates The Quantity Field Of 
        A Part(Adds To The Quantity.)
    */
    void addquant()
    {
         int id,ID,quant;
         fscanf(in,"%d",&id);
         fscanf(in,"%d",&quant);
         ID=binarysearch(id);
            if (ID==-1)
            printf("\nThe Part %d Quantity Cannot be Added. Part Entry Not Found!\n",id);
         else  
            {
             part[ID].quant=part[ID].quant+quant;
            }
    }
    /*****************************************************************************/
    /*  
        The Following Function Checks If There Is Sufficient 
        Quantity Of A Part To Sell, Then Modifies The Quantity
        After Subtracting The Amount To Be Sold.
    */
    void sellpart()
    {     
         int id,ID,quant;
         fscanf(in,"%d",&id);
         fscanf(in,"%d",&quant);
         ID=binarysearch(id);
            if (ID==-1)
            printf("\nThe Part %d Cannot Be Sold. Part Entry Not Found!\n",id);
         else  
            {
              
              if(part[ID].quant<quant)
                 printf("\nThe Part %d Cannot be Sold.Not Enough Stock!\n",id);
              else
              {              
                 part[ID].quant=part[ID].quant-quant; 
                 parts_sold=parts_sold+quant;
                 total=total+(part[ID].price * quant);
              }   
            }  
    }
    /*****************************************************************************/
    /*  
        When Called, This Function Prints The Entire List Of Parts
        Along With The Respective Description,Price And Quantity. 
    */
    void printparts()
    {
         int i;
        
         printf("\nPart ID.\tDescription\t\tCurrent Quantity\tPrice\n\n");
         for (i=0; i<count; i++)
         printf("%d\t\t%-30s\t%d\t\t%5.2f\n",part[i].ID, part[i].desc, part[i].quant, part[i].price);
          
    }
    /*****************************************************************************/
    /*  
        This Function Searches For A Given Key.It Returns The Location Of 
        The Key If Found and -1 If It Isn't Found.
    */
    int binarysearch(int id)
    {    
         int mid,lo=0,hi=count;
         while(lo<=hi)
         {
           mid=(lo+hi)/2;
                 if(part[mid].ID==id)
                 return mid;
            else if(id<part[mid].ID)
                 hi=mid-1;
            else
                 lo=mid+1;                   
         } 
         return -1;
    }
    /*****************************************************************************/

  2. #17
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I thought that was what I did. If you ask a SPECIFIC quesiton on something I posted last time I'll be happy to explain what I meant, but if you just insist on posting different versions of the same code, then I don't really think you actually understand what you're doing.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #18
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    honestly i dont!that's why im just lost and most likely asking stupid questions.all i wanted to know is how do i convert this code that i posted into linked list. it was tough enouh for me to write the program with just structures .Plus u said i had redundant code so i thought i'd fix that one time.my bad. i really would appreciate it if you would explain to me what needs to be done here. i understand the layout of the linked list and how to make new nodes for it but i cant use it.

  4. #19
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Well, the first thing to do is to actually create the data structure that your program is going to use. You could probably just add a next member to your PART structure and use that.

    Code:
    typedef struct PART {
            int    ID;
            char   desc[50];
            int    quant;
            float  price;
            struct PART *next;
            }PART;
    Note that I added a structure tag -- otherwise you can't declare an instance of the structure in itself. This tag can be whatever name you like, I just chose PART again.

    Now you need to modify your functions to support this new data structure. Do it one function at a time. main() never accesses the part[] array, so it requires no modifications. insertinorder() would need changing for sure; but fortunately, insertion into linked lists is quite simple. getdescription() is fine as is; so is addnewpart(). changeprice(), addquant(), and sellpart() would need some small changes, because binarysearch() would no longer be able to return the index of the array. You'd have to return a pointer to the node in the linked list that matched. printparts() would become a simple iteration of the linked list.

    binarysearch() would have to stop living up to its name, because you can't really do a binarysearch on a linked list. You'd have to do a linear search, and that is quite simple as well. You'd also have to return a PART* as well, as I already mentioned, because an index just won't do anymore.

    Does that help you get started?
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #20
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    YES it does i got somewhere to start now.ill check you guys back when i reach somewhere with this.thanks DWK

  6. #21
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    okay i wrote over the insertion sort but i dont think it reads anything.it prints eeverything but the figures are all 0's
    can you tell me where my error is?
    i make a cll in the while statement top= insertinorder(top,tempid);
    tempid was declared as an int.


    Code:
    ptr insertinorder(ptr top,int tempid){
    ptr np,curr,prev,makenode(int);
      np=makenode(tempid);
    prev=NULL;
    curr=top;
    while(curr!=NULL && tempid>curr->num){
    prev=curr;
    curr=curr->next;
    }
    if(prev==NULL){
                            np->next=top;
    return np;}
    np->next=curr;
    prev->next=np;
    return top;
    }

  7. #22
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    okay i give up.this too hard for me il stick to math alone.depressing!

  8. #23
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by nefsan View Post
    okay i give up.this too hard for me il stick to math alone.depressing!
    Well, I guess that's one solution.

    I can't comment on what your code does, as I don't know what makenode does. The insertion sort itself looks about right, although it would only work right if you use it by "top = insertinorder(...)" - it seems better to me to set top in the function itself.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #24
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    ptr insertinorder(ptr top,int tempid){
    ptr np,curr,prev,makenode(int);
      np=makenode(tempid);
    prev=NULL;
    curr=top;
    while(curr!=NULL && tempid>curr->num){
    prev=curr;
    curr=curr->next;
    }
    if(prev==NULL){
                            np->next=top;
    return np;}
    np->next=curr;
    prev->next=np;
    return top;
    }
    If prev is NULL, then top would have to be NULL. Think about it. It means that you can just assign NULL to np->next rather than assigning top.

    And you never assign tempid to anything, which would no doubt explain why you always get zeros. Use
    Code:
    np->num = tempid;
    somewhere, if you don't elsewhere in the code. Show us the code that calls this function, so we can see how np is initialized.

    How are you printing the linked list? There could be problems with that code as well.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Linked list program need help !!!
    By dcoll025 in forum C++ Programming
    Replies: 1
    Last Post: 04-20-2009, 10:03 AM
  2. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 08:04 PM
  3. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  4. Template Class for Linked List
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-04-2001, 09:07 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM