Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# C Programming Link List problem

Posted on 2007-11-26
Medium Priority
223 Views
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;

scanf("%s", &poly1);

{
printf("Cannot allocate memory"  ;
return (-1);
}

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;
do
{
printf("the coeff &#xcn;",temp->coeff);
printf("the exp &#xcn;",temp->exp);
temp = temp->next;
}while(temp != NULL);
scanf("%i",&i);
return 0;
}
``````
0
Question by:SteveZz
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 4
• 3
• 2
• +1

LVL 8

Expert Comment

ID: 20355505

``````// Line 45: This seems to do nothing...
poly1new->next = poly1new->next;

// Did you intend to write:
poly1new->next = &poly1new;

// ?
``````
0

LVL 10

Accepted Solution

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

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

0

LVL 8

Expert Comment

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

LVL 53

Expert Comment

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

scanf("%s", &poly1);

That should be :

scanf("%s", poly1);

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

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

LVL 53

Expert Comment

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

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           *
*          *poly1new      Pointer used to traverse the first polynomial        *
*          *poly2new      Pointer used to traverse the second polynomial       *
*          *anspoly       Pointer to 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;

/* Ask the user to input the first polynomial */

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

/* Ask the user to input the second polynomial */

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

/* Allocate memory for the beginning of the linked list holding polynomial 1 */

/* If memory allocation was unsuccessful print error and quit the program */
{
printf("Cannot allocate memory");
return (-1);
}

/* Make the poly1new pointer point to the head of the list */

/* 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 */

/* If memory allocation was unsuccessful print error and quit the program */
{
printf("Cannot allocate memory");
return (-1);
}

/* Make the poly2new pointer point to the head of the list */

/* 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 */

/* If memory allocation was unsuccessful print error and quit the program */
{
printf("Cannot allocate memory");
return (-1);
}

/* Make the poly2new pointer point to the head of the list */

/* Create temp pointers to the heads of both polynomials */

/* 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;

/* 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

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

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

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

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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were smallâ€¦
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and infâ€¦
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.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
###### Suggested Courses
Course of the Month5 days, 20 hours left to enroll