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

This is a discussion on Same Questiion But I Do Not Know How To Do It In Linked List. within the C Programming forums, part of the General Programming Boards category; A parts company has information on its parts in a data file "parts.dat". The data in the data file is ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    56

    Thumbs down Same Questiion But I Do Not Know How To Do It In Linked List.

    A parts company has information on its parts in a data file "parts.dat". The data in the data file is structured as follows:



    The data file consists of 2 parts. The first part has information on the parts. Each line of data contains the part number ( an integer), a description of the part, the quantity in stock and the unit price separated by one or more spaces. The description of the part is contained within two '*' ( the asterisks are not part of the description). This section of data is terminated by a line with a single 0.



    The next half of the data file consists of transactions performed on the data. Each line consists of two letters indicating the transaction to be performed and this is followed by data relevant for the transaction. The different kinds of transactions are as follows:



    1. To add a new part:

    ap partNumber *description* quantityInStock unitPrice



    2. To sell a part:

    sp partNumber quantitySold



    3. To change the price of a part:

    cp partNumber newPrice



    4. To add stock of a particular part:

    cq partNumber quantityToAdd



    5. To list all information on all parts:

    ls

    YOUR PROGRAM MUST USE A LINKED STRUCTURE THAT MAINTAINS THE LIST IN SORTED ORDER BY PART NUMBER .
    YOUR PROGRAM MUST CATER FOR CASES WHERE THERE IS NOT ENOUGH QUANTITY IN STOCK FOR A SALE ,OR THE PART NUMBER DOES NOT EXIST .IN THESE CASES ,APPROPRIATE ERROR MESSAGES MUST BE PRINTED

    YOUR PROGRAM MUST ALSO PRINT AFTER PROCESSING ALL THE TRANSACTIONS THE TOTAL SALES FIGURE




    An example of the format of the data file is given below.
    .


    2345 *Stanley Bearing* 178 12.56

    3456 *Silver Rims* 4 500.00

    7862 *Castrol GTX 50 Body Engine Oil* 29 20

    0

    ap 9872 *BrakeShoes* 50 2241.00

    ls

    sp 2345 58

    sp 7862 15

    cq 2345 100

    cp 7862 19.59

    ls


    I GOT ALOT OF TROUBLE WITH STRUCTURES JUST A WEEK AGO NOW HOW THE HECK DO I DO THIS ONE?IS IT POSSIBLE TO MODIFY MY STRUCTURE PROGRAM TO A LKINK LIST ONE? HELP

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Here's the other thread in question: need some help!!

    It seems that you already know how to solve the problem, at least in one way. So perhaps you just need some basic information about linked lists? If so, why not try http://www.google.ca/search?hl=en&q=...e+Search&meta=
    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.

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Quote Originally Posted by nefsan View Post
    IS IT POSSIBLE TO MODIFY MY STRUCTURE PROGRAM TO A LKINK LIST ONE? HELP

    Try asking ADIDAS, they say that impossible is nothing......

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    ADIDAS? You mean sportswear?

    IS IT POSSIBLE TO MODIFY MY STRUCTURE PROGRAM TO A LKINK LIST ONE? HELP
    Sure, rather than using part[i++], just add a call to add_part_to_linked_list(). But you need to know how linked lists work first . . .

    Have you tried anything?
    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. #5
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Though i would like to give you a hand, watch my code which is not complete, you may get some ideas about how to save things in a array of structs, later we discuss about linked lists.
    Well this not complete function tries to read from file the data and store them in an array of structs, also it returns the array or NULL if error exists.

    Code:
    #define BUFFER_SIZE 1024
    #define OFFSET 3
    
    
    typedef struct p_struct
    {
    	int partNumber;
    	char description[128];
    	int quantityStock;
    	float unitPrice;
    }PartStruct;
    
    
    PartStruct* ReadFromFile(const char *filename)
    {
    	if(filename == NULL)
    		return NULL;
    	else
    	{
    		FILE *file = fopen(filename , "r");
    		if(file == NULL)
    		{
    			fprintf(stderr, "Error in opening '%s' file.\n", filename);
    			return NULL;
    		}
    		else
    		{
    			//Index.
    			int i = 0;
    			int j = 0;
    			static int error = 0;
    			//Strtok pointer.
    			char *ptrTok = NULL;
    			//Array to hold the data from file.
    			char buffer[BUFFER_SIZE];
    			//Our array of structs.
    			PartStruct *ptrParts = NULL;
    			//Get init space.
    			ptrParts = calloc(1, sizeof(PartStruct));
    			if(ptrParts == NULL)
    				return NULL;
    			//Initialise buffer.
    			memset(buffer, 0 , BUFFER_SIZE);
    			while(1)
    			{
    				if(fgets(buffer, sizeof(buffer), file) == NULL)
    					break;
    				if(buffer[0] == '\n')
    					continue;
    				if(buffer[0] == '0')
    					break;
    				if(buffer[strlen(buffer)-1] == '\n')
    					buffer[strlen(buffer)-1] = '\0';
    				//Tokens.
    				ptrTok = strtok(buffer, " *");
    				if(ptrTok == NULL)
    				{
    					error = 1;
    					break;
    				}
    				else
    				{
    					if(sscanf(ptrTok,"%d",&ptrParts[i].partNumber) != 1)
    					{
    						error = 2;
    						break;
    					}
    					while(ptrTok != NULL && j < OFFSET)
    					{
    						ptrTok = strtok(NULL, " *");
    						switch(j)
    						{
    							case 0:
    							case 1:
    							case 2:
    
    							default:
    							//Error.
    						}
    						//Advance j.
    						j++;
    					}
    				}
    				//Should realloc here.
    				i++;
    				ptrParts = realloc(ptrParts, (i+1) * sizeof(PartStruct));
    			}
    			//Close file.
    			fclose(file);
    			//Return the struct.
    			if(!error)
    				return ptrParts;
    			else
    			{
    				free(ptrParts);
    				return NULL;
    		                }
    		}
    	}
    }
    Last edited by Bokarinho; 10-06-2007 at 07:23 PM. Reason: Just nothing!!!

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Code:
    PartStruct* ReadFromFile(const char *filename)
    {
    	if(filename == NULL)
    		return NULL;
    	else
    	{
    		FILE *file = fopen(filename , "r");
    		if(file == NULL)
    		{
    			fprintf(stderr, "Error in opening '&#37;s' file.\n", filename);
    			return NULL;
    		}
    		else
    		{
    		/* ... */
    Those elses are useless, and add extra levels of indentation to the rest of the code, which should probably be avoided if possible.

    Code:
    			ptrParts = calloc(1, sizeof(PartStruct));
    			if(ptrParts == NULL)
    				return NULL;
    What about closing the file?
    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.

  7. #7
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Quote Originally Posted by dwks View Post
    Code:
    PartStruct* ReadFromFile(const char *filename)
    {
    	if(filename == NULL)
    		return NULL;
    	else
    	{
    		FILE *file = fopen(filename , "r");
    		if(file == NULL)
    		{
    			fprintf(stderr, "Error in opening '%s' file.\n", filename);
    			return NULL;
    		}
    		else
    		{
    		/* ... */
    Those elses are useless, and add extra levels of indentation to the rest of the code, which should probably be avoided if possible.

    Code:
    			ptrParts = calloc(1, sizeof(PartStruct));
    			if(ptrParts == NULL)
    				return NULL;
    What about closing the file?
    Yes you are right, of course i ment adidas sportwear, with messi they say impossible is nothing,the else statements i use are correct they help me in writing my code and organise it in my brain better, i agree they may are not the best choice but there is no fault with it. Am i right?

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    No, no, if you like the else statements then that's fine too. They're just redundant, and like I said involve more indentation.
    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.

  9. #9
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    How to read the data from file into your structure, its a complicated way using fgets() and strings, someone else could happily use fscanf() but i just wanted to get some practise with tokens. Well thats the prog:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <conio.h>
    
    #define BUFFER_SIZE 1024
    #define OFFSET 3
    
    typedef struct p_struct
    {
    	int partNumber;
    	char description[128];
    	int quantityStock;
    	float unitPrice;
    }PartStruct;
    
    PartStruct* ReadFromFile(const char *filename, int *ptrPartSize)
    {
    	if(filename == NULL)
    		return NULL;
    	else
    	{
    		FILE *file = fopen(filename , "r");
    		if(file == NULL)
    		{
    			fprintf(stderr, "Error in opening '%s' file.\n", filename);
    			return NULL;
    		}
    		else
    		{
    			//Index.
    			int i = 0;
    			int j = 0;
    			static int error = 0;
    			//Strtok pointer.
    			char *ptrTok = NULL;
    			//Array to hold the data from file.
    			char buffer[BUFFER_SIZE];
    			//Our array of structs.
    			PartStruct *ptrParts = NULL;
    			//Get init space.
    			ptrParts = calloc(1, sizeof(PartStruct));
    			if(ptrParts == NULL)
    				return NULL;
    			//Initialise buffer.
    			memset(buffer, 0 , BUFFER_SIZE);
    			while(1)
    			{
    				if(fgets(buffer, sizeof(buffer), file) == NULL)
    					break;
    				if(buffer[0] == '\n')
    					continue;
    				if(buffer[0] == '0')
    					break;
    				if(buffer[strlen(buffer)-1] == '\n')
    					buffer[strlen(buffer)-1] = '\0';
    				//Tokens.
    				ptrTok = strtok(buffer, " *");
    				if(ptrTok == NULL)
    				{
    					error = 1;
    					break;
    				}
    				else
    				{
    					if(sscanf(ptrTok,"%d",&ptrParts[i].partNumber) != 1)
    					{
    						error = 2;
    						break;
    					}
    					while(ptrTok != NULL && j < OFFSET)
    					{
    						ptrTok = strtok(NULL, " *");
    						switch(j)
    						{
    							case 0:
    									//Its a bit strange to use this technique only knowing the way the
    									//data stored in the file. <fscanf may become a better solution.>
    									strcpy(&ptrParts[i].description, ptrTok);
    									ptrTok = strtok(NULL, "*");
    									ptrParts[i].description[strlen(ptrParts[i].description)] = ' ';
    									strcat(&ptrParts[i].description, ptrTok);
    								break;
    							case 1:
    								sscanf(ptrTok,"%d",&ptrParts[i].quantityStock);
    								break;
    							case 2:
    								sscanf(ptrTok,"%f",&ptrParts[i].unitPrice);
    								break;
    							default:
    								printf("Error.\n");
    								error = 3;
    								break;
    						}
    						//Advance j.
    						j++;
    					}
    				}
    				//Should realloc here.
    				i++;
    				ptrParts = realloc(ptrParts, (i+1) * sizeof(PartStruct));
    				//Remember to get j to zero.
    				j = 0;
    			}
    			//Close file.
    			fclose(file);
    			//Return the struct.
    			if(!error)
    			{
    				*ptrPartSize = i;
    				return ptrParts;
    			}
    			else
    			{
    				free(ptrParts);
    				return NULL;
                }
    		}
    	}
    }
    int main(int argc, char* argv[])
    {
    	int i;
    	int r_size = 0;
    	PartStruct *r = ReadFromFile("parts.txt", &r_size);
    	for(i = 0; i < r_size; i++)
    		printf("%d %s %d %f\n", r[i].partNumber, r[i].description, r[i].quantityStock, r[i].unitPrice);
    	free(r);
    	printf("Hit any key to exit........");
    	getch();
    	return 0;
    }

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    conio.h . . . last time I looked that had "died with the dinosaurs", as Salem once said . . .

    Code:
    				i++;
    				ptrParts = realloc(ptrParts, (i+1) * sizeof(PartStruct));
    I didn't really look at it, but I think that you're allocating one too many elements there. Usually the statements go the other way around.
    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.

  11. #11
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    Code:
     10-07-2007, 03:42 AM    #9  
    Bokarinho 
    Registered User
     
    
    Join Date: Jun 2007
    Posts: 47  How to read the data from file into your structure, its a complicated way using fgets() and strings, someone else could happily use fscanf() but i just wanted to get some practise with tokens. Well thats the prog:
    
    
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <conio.h>
    
    #define BUFFER_SIZE 1024
    #define OFFSET 3
    
    typedef struct p_struct
    {
    	int partNumber;
    	char description[128];
    	int quantityStock;
    	float unitPrice;
    }PartStruct;
    
    PartStruct* ReadFromFile(const char *filename, int *ptrPartSize)
    {
    	if(filename == NULL)
    		return NULL;
    	else
    	{
    		FILE *file = fopen(filename , "r");
    		if(file == NULL)
    		{
    			fprintf(stderr, "Error in opening '%s' file.\n", filename);
    			return NULL;
    		}
    		else
    		{
    			//Index.
    			int i = 0;
    			int j = 0;
    			static int error = 0;
    			//Strtok pointer.
    			char *ptrTok = NULL;
    			//Array to hold the data from file.
    			char buffer[BUFFER_SIZE];
    			//Our array of structs.
    			PartStruct *ptrParts = NULL;
    			//Get init space.
    			ptrParts = calloc(1, sizeof(PartStruct));
    			if(ptrParts == NULL)
    				return NULL;
    			//Initialise buffer.
    			memset(buffer, 0 , BUFFER_SIZE);
    			while(1)
    			{
    				if(fgets(buffer, sizeof(buffer), file) == NULL)
    					break;
    				if(buffer[0] == '\n')
    					continue;
    				if(buffer[0] == '0')
    					break;
    				if(buffer[strlen(buffer)-1] == '\n')
    					buffer[strlen(buffer)-1] = '\0';
    				//Tokens.
    				ptrTok = strtok(buffer, " *");
    				if(ptrTok == NULL)
    				{
    					error = 1;
    					break;
    				}
    				else
    				{
    					if(sscanf(ptrTok,"%d",&ptrParts[i].partNumber) != 1)
    					{
    						error = 2;
    						break;
    					}
    					while(ptrTok != NULL && j < OFFSET)
    					{
    						ptrTok = strtok(NULL, " *");
    						switch(j)
    						{
    							case 0:
    									//Its a bit strange to use this technique only knowing the way the
    									//data stored in the file. <fscanf may become a better solution.>
    									strcpy(&ptrParts[i].description, ptrTok);
    									ptrTok = strtok(NULL, "*");
    									ptrParts[i].description[strlen(ptrParts[i].description)] = ' ';
    									strcat(&ptrParts[i].description, ptrTok);
    								break;
    							case 1:
    								sscanf(ptrTok,"%d",&ptrParts[i].quantityStock);
    								break;
    							case 2:
    								sscanf(ptrTok,"%f",&ptrParts[i].unitPrice);
    								break;
    							default:
    								printf("Error.\n");
    								error = 3;
    								break;
    						}
    						//Advance j.
    						j++;
    					}
    				}
    				//Should realloc here.
    				i++;
    				ptrParts = realloc(ptrParts, (i+1) * sizeof(PartStruct));
    				//Remember to get j to zero.
    				j = 0;
    			}
    			//Close file.
    			fclose(file);
    			//Return the struct.
    			if(!error)
    			{
    				*ptrPartSize = i;
    				return ptrParts;
    			}
    			else
    			{
    				free(ptrParts);
    				return NULL;
                }
    		}
    	}
    }
    int main(int argc, char* argv[])
    {
    	int i;
    	int r_size = 0;
    	PartStruct *r = ReadFromFile("parts.txt", &r_size);
    	for(i = 0; i < r_size; i++)
    		printf("%d %s %d %f\n", r[i].partNumber, r[i].description, r[i].quantityStock, r[i].unitPrice);
    	free(r);
    	printf("Hit any key to exit........");
    	getch();
    	return 0;
    }
    is that linked lists??i thought u needed stuff like "last->next" etc.can someone modify this proogram to use linked list instead ?
    Code:
    ////RAJIV RAMKHALAWAN
    //ID:806001754
    //ASSIGNMENT 1
    
    
    
    
    
    
    
    #include <stdio.h>
    
    typedef struct
    {
       int partnum;
       char desc[50];
       int qtyInStock;
       double unitPrice;
    } part_info;
    
    #define MAX 50
    part_info part[MAX];
    
    int main()
    {
        void readDesc(FILE * in, char data[]);
        void AddInOrder(int i);
        
        FILE * in = fopen("parts.dat","r");
        
        if (in == NULL)
        {
            printf("File not found: parts.dat\n");
            system("pause");
            return 1;
        }
        
        
        
        int id, i=0, finished=0;
        double TotalSales=0;
        char trans[3];
        fscanf(in,"%d",&id);
        
        while (id != 0 && i<MAX)
        {
              part[i].partnum = id;
              readDesc(in, part[i].desc);
              fscanf(in,"%d",&part[i].qtyInStock);
              fscanf(in,"%lf",&part[i].unitPrice); 
              if (i>0) AddInOrder(i);         
              i++;
              fscanf(in,"%d",&id);
        }
        
        while (finished==0)
        {
            char ch=getc(in);
            while (ch== ' ') 
                  ch=getc(in);
                  
            trans[0]=getc(in);
            
            if (trans[0] != EOF) 
            {
               trans[1]=getc(in);
               trans[2]='\0';
                          
               if (strcmp(trans,"ls")==0)
               {
                  printf("\nPart No.\tDescription\t\tQuantity in Stock\tPrice\n\n");
                  int j;
                  for (j=0; j<i; j++)
                  printf("%d\t\t%-30s\t%d\t\t%5.2lf\n",part[j].partnum, part[j].desc, part[j].qtyInStock, part[j].unitPrice);
                  
               }
               else
               if (strcmp(trans,"sp")==0)
               {
                  int j, pnum, qsold;
                  fscanf(in,"%d",&pnum);
                  fscanf(in,"%d",&qsold);
                  for (j=0; j<i; j++)
                  {
                      if (part[j].partnum > pnum)
                      {
                         printf("\nPart Number not found: %d!!!\n",pnum);
                         break;
                      }
                      else
                      if (part[j].partnum == pnum)
                      {
                         if (part[j].qtyInStock < qsold)
                         {
                            printf("\nNot enough quantity in stock!!!\n");
                            break;
                         }
                         else
                         {
                             part[j].qtyInStock-=qsold;
                             TotalSales+= (part[j].unitPrice * qsold);
                             break;
                         }
                      }
                  }              
               }
               else
               if (strcmp(trans,"ap")==0)
               {
                      fscanf(in,"%d",&part[i].partnum);
                      readDesc(in, part[i].desc);
                      fscanf(in,"%d",&part[i].qtyInStock);
                      fscanf(in,"%lf",&part[i].unitPrice); 
                      if (i>0) AddInOrder(i);         
                      i++;
                      
               }
               else
               if (strcmp(trans,"cp")==0)
               {
                  int j, pnum, nprc;
                  fscanf(in,"%d",&pnum);
                  fscanf(in,"%d",&nprc);
                  for (j=0; j<i; j++)
                  {
                      if (part[j].partnum > pnum)
                      {
                         printf("\nPart Number not found: %d....\n",pnum);
                         break;
                      }
                      else
                      if (part[j].partnum == pnum)
                      {                     
                             part[j].unitPrice=nprc;                         
                             break;                   
                      }
                  }              
               }
               else
               if (strcmp(trans,"cq")==0)
               {
                  int j, pnum, qty;
                  fscanf(in,"%d",&pnum);
                  fscanf(in,"%d",&qty);
                  for (j=0; j<i; j++)
                  {
                      if (part[j].partnum > pnum)
                      {
                         printf("\nPart Number not found: %d....\n",pnum);
                         break;
                      }
                      else
                      if (part[j].partnum == pnum)
                      {                     
                             part[j].qtyInStock+=qty;                        
                             break;                   
                      }
                  }              
               }
               
            } 
            else
               finished=1;
        }
        
        printf("\nTotal Sales: %5.2lf\n",TotalSales);
        
        getchar();
        return 0;
    }
    /////////////////////////////..........................FUNCTION TO SORT
    void AddInOrder(int i)
    {
         int j=i;
         part_info temp;
         
         while (j>=0 && (part[i].partnum < part[j-1].partnum))
         {
               temp=part[j];
               part[j] = part[j-1];
               part[j-1] = temp;
               j--;
         }     
    }
    ///////////////////////////..............................FUNCTION TO READ FILE
    void readDesc(FILE * in, char data[])
    {
         char c;
         int i=0;
         
         c=getc(in);     
         while (c != '*') c=getc(in);
         
         c=getc(in);
         data[i]=c;
         
         c=getc(in);
         while (c != '*') 
         {
               i++;
               data[i]=c;
               c=getc(in);
         }
         i++;
         data[i]='\0';     
    }

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I don't see any linked list in there - which bit do YOU think does a linked list.

    --
    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.

  13. #13
    Registered User
    Join Date
    Oct 2007
    Posts
    56
    well i think that i need to read the numbers and sort it and then enter it into the linked list.but im not sure how to read and sort the entire string into the linked list. this is my function code for sorting and adding to the end of the list.i can sort and insert using just interges that i enter but i cant read and sort the string into the list.any thoughts on how to do it?
    Code:
    typedef struct node{
    int num;
    struct node*next;
    }Node, *Nodeptr;
    ..................................//function to ad in place
    
    Nodeptr makenode(int n){
    Nodeptr np=(Nodeptr) malloc (sizeof(Node));
    np->num=n;
    np->next=NULL;
    return np;}
    
    Nodeptr addinplace(Nodeptr top, int n){
    np=makenode(n);
    prev=NULL;
    curr=top;
    while(curr!=NULL && n>curr->num){
    prev=curr;
    curr=curr->next;
    }
    if(prev==NULL){
                            np->next=top;
    return np;}
    np->next=curr;
    prev->next=np;
    return top;
    }

  14. #14
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Use better indentation, for one thing.

    i can sort and insert using just interges that i enter but i cant read and sort the string into the list.any thoughts on how to do it?
    If you can do it with ints, you can do it with strings. You just have to use functions from <string.h> like strcpy() and strcmp().
    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.

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    So, assuming your current method for reading data works OK (I can't tell if it does or not by just looking at the code, but I presume you have tested it??)

    So you already have a way to read the line into a part_info, correct?

    Now, all you need to do is change the way that you store the part_info from an array into a linked list.

    There are two ways to do this: You can either add a the link into your part_info struct, or define a second struct, which has a link and a part_info component - here we get a further choice of either containing the part_info directly in the struct, or using a pointer to it.

    I would suggest that the least intrusion is by just adding a link (called "next") into your part_info structure.

    Then as you read the data, insert it (at the right place?) into the linked list, and modify your code that searches the array to search the list instead.

    May I also suggest that you create a function to search for an item, instead of duplicating code to find a part number several times in your code. [It woudl have been far easier to change your code if you had done that in the first place, as that would have meant that you wouldn't have to change very much at all].

    --
    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.

Page 1 of 2 12 LastLast
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, 11:03 AM
  2. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 09:04 PM
  3. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 11: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, 11:21 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21