Solved

C Programming Link List problem

Posted on 2007-11-26
10
214 Views
Last Modified: 2010-04-15
My code shown below is attempting to take in a line of code for a polynomial in the form +6*X^2-3*X^1

I have to create a linked list of this and then attempt to add it to another list of a polynomial. In the code below as it reads in the coefficients and exponents it echo prints them and works correctly. My problem is when we enter the do while loop. I make a temp pointer = to the head of the polynomial linked list. when I do this and attempt to print the only output is the last part of the polynomial telling me that the coeff is 3 and exp is 1.

This is what is shown when the program runs

+6*X^2-3*x^1
The Coeff 6
The Exp 2
The Coeff 3
The Exp 1
the coeff 3
the exp 1


notice how 6 and 2 aren't display in the while loops output.

What am I doing wrong, why isnt the head pointing to the head?

Thanks for any help
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define max 300
 
 

struct term

{

char coeff;

char exp;

struct term *next;

};
 

int main()

{
 

char poly1[max], poly2[max], anspoly[max];

int length, i;
 
 

struct term *poly1head, *poly2head, *poly3head, *poly1new, *poly2new, *poly3new;

scanf("%s", &poly1);
 

poly1head = malloc(sizeof(struct term));

if(poly1head == NULL)

{

printf("Cannot allocate memory"  ;

return (-1);

}
 

poly1new = poly1head;

length = strlen(poly1);

for(i = 0; i < length; i++)

{

if((poly1 == '-') || (poly1 == '+'))

{ 

poly1new->coeff = poly1[i + 1];

printf("The Coeff &#xcn;",poly1new->coeff);

}

else if(poly1 == '^')

{

poly1new->exp = poly1[i + 1];

printf("The Exp &#xcn;",poly1new->exp);

poly1new->next = malloc(sizeof(struct term));

poly1new->next = poly1new->next;

}

else

poly1new->next = NULL;

}

struct term *temp;

temp = poly1head;

do

{

printf("the coeff &#xcn;",temp->coeff);

printf("the exp &#xcn;",temp->exp);

temp = temp->next;

}while(temp != NULL);

scanf("%i",&i);

return 0;

}

Open in new window

0
Comment
Question by:SteveZz
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 8

Expert Comment

by:Thejaka
ID: 20355505

// Line 45: This seems to do nothing...

poly1new->next = poly1new->next;
 

// Did you intend to write:

poly1new->next = &poly1new;
 

// ?

Open in new window

0
 
LVL 10

Accepted Solution

by:
margajet24 earned 20 total points
ID: 20355712
poly1new->next = poly1new->next;

replace :
poly1new->next = poly1new->next;
to:
poly1new = poly1new->next;

0
 
LVL 8

Expert Comment

by:Thejaka
ID: 20355819
Ah yes... margajet24's right. I should have gone through the code properly :o
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20356320
1) You've got a serious problem here :

        scanf("%s", &poly1);

    That should be :

        scanf("%s", poly1);

    since poly1 is already interpreted as a pointer (&poly1 would take the address of the address).

    As a consequence you'll also have to change the rest of the code accordingly, like this line :

        if((poly1 == '-') || (poly1 == '+'))

    poly1 is an address, NOT a char.


2) There's a problem in this line :

        printf("Cannot allocate memory"  ;

    I'm sure you can spot it ;) And if not, your compiler will tell you.


3) This printf uses a wrong format :

        printf("The Coeff &#xcn;",poly1new->coeff);

    You probably meant :

        printf("The Coeff %c\n",poly1new->coeff);

    Same elsewhere.



These were just the syntactic problems. margajet24 already pointed out one thing you have to fix in order to correctly add new nodes. But that still won't make your program function correctly. Your string parsing code is not fully functioning. You have to make the fix I suggested in 1), and then also make sure you account for - signs, for values longer than 1 character, for spaces, etc.

Give it a go, and post your new code here, so we can ahve a look at it and help you further.
0
 
LVL 3

Author Comment

by:SteveZz
ID: 20357977
Infinity08: I had those things in correctly in my program apparently when I posted it the brackets were removed, but thank you for your help.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 53

Expert Comment

by:Infinity08
ID: 20358004
>> I had those things in correctly in my program apparently when I posted it the brackets were removed, but thank you for your help.

I'm not convinced. The missing ) was a minor issue. The issue I pointed out in 1) however is a MAJOR issue, and you SHOULD fix it.

Can you post the code you're using now ? Just to put my mind at ease ?
0
 
LVL 3

Author Comment

by:SteveZz
ID: 20361571
I will try but we'll see what happens when I post it.  The code works now.  The issue you pointed out in number one I was told to use the & before anytime I was reading in values.

*                                                                              *
* This program adds two polynomials inputted by the user.  It then outputs the *
* resulting polynomial.                                                        *
*                                                                              *
* Variable Directory:                                                          *
*   struct term           a struct to hold each term of a polynomial           *
*   - char coeff          Coefficient                                          *
*   - char sign           Sign of each coefficient                             *
*   - char exp            Exponent to each term                                *
*   struct term *next     Pointer to the next term in the polynomial           *
*          *poly1head     Head of the first polynomial linked list             *
*          *poly2head     Head of the second polynomial linked list            *
*          *poly1new      Pointer used to traverse the first polynomial        *
*          *poly2new      Pointer used to traverse the second polynomial       *
*          *anspoly       Pointer to the answer polynomial                     *
*          *anspolyhead   Pointer to the head of the answer polynomial         *
*          *temp          Pointer to traverse the list for printing of poly1   *
*          *temp2         Pointer to traverse the list for printing of poly2   *
*          *temp3         Pointer to traverse the list for printing of anspoly *
*   char poly1[]          String of the first polynomial                       *
*        poly2[]          String of the second polynomial                      *
*   int length            Length of the string                                 *
*       i                 Index Value                                          *
*******************************************************************************/

/* Load standard libraries define max array size */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 300

/* Form the layout for the struct term */
struct term
{
   char coeff;
   char sign;
   char exp;
   struct term *next;
};

int main()
{
/* Variable Declarations */
  char poly1[max], poly2[max];
  int length, i;
  struct term *poly1head, *poly2head, *poly1new, *poly2new, *anspoly,
              *anspolyhead, *temp, *temp2, *temp3;

/* Ask the user to input the first polynomial */
  printf("Please enter the first polynomial\n");

/* Read in the first polynomial as a string */
  scanf("%s", &poly1);

/* Ask the user to input the second polynomial */
  printf("\nPlease enter the second polynomial\n");

/* Read in the second polynomial as a string */
  scanf("%s", &poly2);

/* Allocate memory for the beginning of the linked list holding polynomial 1 */
  poly1head = malloc(sizeof(struct term));

/* If memory allocation was unsuccessful print error and quit the program */
  if(poly1head == NULL)
    {
      printf("Cannot allocate memory");
      return (-1);
    }
   
/* Make the poly1new pointer point to the head of the list */
  poly1new = poly1head;

/* Find the length of the polynomial string entered by the user */
  length = strlen(poly1);

/* For loop placing the string into the linked list */
  for(i = 0; i < length; i++)
     {
/* If the value in the string is a plus sign */
       if(poly1[i] == '+')
           {    

/* Place the following value into the coefficient location of the term */
           poly1new->coeff = poly1[i + 1];
            
/* Place a plus sign in the corrosponding place for sign of the coeff */
                 poly1new->sign = '+';
         }

/* Else if the value stored in the current string location is a minus */
  else if(poly1[i] == '-')
            {    

/* Place the following value into the coefficient location of the term */
           poly1new->coeff = poly1[i + 1];

/* Place a minus sign in te corrosponding place for the sign of the coeff */
               poly1new->sign = '-';
         }

/* Else if the current value is a ^ */
  else if(poly1[i] == '^')
         {

/* Insert the following term into the exponent location */
             poly1new->exp = poly1[i + 1];
      
/* Allocate memory for the next term */
           poly1new->next = malloc(sizeof(struct term));
        
/* Change the pointer to the next term */
           poly1new = poly1new->next;
         }
    }

/* When the linked list is complete add NULL to the next one */
  poly1new->next = NULL;
   
/* Allocate space for the beginning of the next linked list */
  poly2head = malloc(sizeof(struct term));

/* If memory allocation was unsuccessful print error and quit the program */
  if(poly2head == NULL)
    {
      printf("Cannot allocate memory");
      return (-1);
    }
   
/* Make the poly2new pointer point to the head of the list */
  poly2new = poly2head;

/* Find the length of the polynomial string entered by the user */
  length = strlen(poly2);

/* For loop placing the string into the linked list */
  for(i = 0; i < length; i++)
     {
/* If the value in the string is a plus sign */
       if(poly2[i] == '+')
             {    
/* Place the following value into the coefficient location of the term */
           poly2new->coeff = poly2[i + 1];

/* Place a plus sign in the corrosponding place for sign of the coeff */
               poly2new->sign = '+';
         }

/* Else if the value stored in the current string location is a minus */
  else if(poly1[i] == '-')
           {  

/* Place the following value into the coefficient location of the term */
               poly2new->coeff = poly2[i + 1];
            
/* Place a minus sign in the corrosponding place for sign of the coeff */
               poly2new->sign = '-';
         }      
      
/* Else if the current value is a ^ */
  else if(poly2[i] == '^')
         {

/* Insert the following term into the exponent location */
             poly2new->exp = poly2[i + 1];
        
/* Allocate memory for the next term */
           poly2new->next = malloc(sizeof(struct term));
        
/* Change the pointer to the next term */
           poly2new = poly2new->next;
         }
      }

/* When the linked list is complete add NULL to the next one */
  poly2new->next = NULL;

/* Allocate space for the beginning of the answer linked list */
  anspolyhead = malloc(sizeof(struct term));

/* If memory allocation was unsuccessful print error and quit the program */
  if(anspolyhead == NULL)
    {
      printf("Cannot allocate memory");
      return (-1);
    }
 
/* Make the poly2new pointer point to the head of the list */
  anspoly = anspolyhead;

/* Create temp pointers to the heads of both polynomials */
  temp = poly1head;
  temp2 = poly2head;

/* While temp and temp2 are both not NULL */
  while((temp != NULL)&&(temp2 != NULL))
       {
        
/* If the exponents match on both polynomials */
         if(temp->exp == temp2->exp)
           {
              
/* If the sign of the first polynomial is negative */
               if(temp->sign == '-')
                     
/* Subtract the second from the first */                    
                  anspoly->coeff = temp2->coeff - temp->coeff;

/* If the sign of the second polynomial is negative */               
               else if(temp2->sign == '-')
                     
/* Subtract the first from the second */
                      anspoly->coeff = temp->coeff - temp2->coeff;      
              
/* Else add the coefficients */
                 else
                anspoly->coeff = temp2->coeff + temp->coeff;      
          
/* copy the exponents */
                 anspoly->exp = temp->exp;
                
/* Change to the next term of each polynomial */
               temp = temp->next;
             temp2 = temp2->next;
          }

/* If the exponent of the first polynomial is larger than the second */
        else if(temp->exp > temp2->exp)
          {
/* Copy the first polynomial to the answer and increment the first polynomial */
              anspoly->coeff = temp->coeff;
              anspoly->sign = temp->sign;
              anspoly->exp = temp->exp;
              temp = temp->next;
          }
       
/* Else if the second polynomial's exponent is larger than the first */
        else if(temp2->exp > temp->exp)
          {
/* Copy the second polynomial to the answer and increment to the next term */
              anspoly->coeff = temp2->coeff;
              anspoly->sign = temp2->sign;
            anspoly->exp = temp2->exp;
              temp2 = temp2->next;
          }
/* Allocte memory for the next space of the answer list */
        anspoly->next = malloc(sizeof(struct term));
        anspoly = anspoly->next;
     }
     
/* Make the end of the linked list point to NULL */
  anspoly->next = NULL;
 
/*Make a temp pointer to the head of the answer */
  temp3 = anspolyhead;
 
/* Print comment to user */
  printf("\nAfter adding the two polynomials you inputted the resulting polynomial is:\n");

/* While the end of the list is not reached */
  while(temp3->next != NULL)
       {
/* If the coefficient is not zero */
         if(temp3->coeff != 0)
           {
/* If the sign of the coefficient is negative print a minus sign */
             if(temp3->sign == '-')
                printf("-");
/* Else print a plus */
             else
                printf("+");
/* Print the coefficient */
             printf("%c", temp3->coeff);
/* If the exponent is greater than one print it */
             if(temp3->exp > '1')
                printf("*X^%c", temp3->exp);
/* If the exponent is 1 just print X */
             else if(temp3->exp == '1')
                printf("X");
           }
/* Move to the next node */
         temp3 = temp3->next;
       }
  return 0;
}

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20361659
>> The issue you pointed out in number one I was told to use the & before anytime I was reading in values.

poly1 already degrades to the address, so there's no need to use &.

You've misunderstood what you've been taught : When using scanf, the parameters have to be addresses of the values you want to read. Usually, that means you have to use & to get the address. However, strings are a special case - their identifier ALREADY represents the address, so there's no need for the & operator - in fact you can get confused and really mess up the application at runtime.


I'm glad to see you fixed the other problems I mentioned.
0
 
LVL 3

Author Comment

by:SteveZz
ID: 20367871
Can anyone explain to me the issue I'm currently having.  The program above works when I compile using GCC.  when I move to Dev CPP and test out the program.  The result prints out however the while loop runs longer than it should.  At the end of the code it prints out ++ at the end.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 20367969
Which loop are you referring to ? What was the input ? What was the expected output ?
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now