@@ -30,17 +30,11 @@ struct term
30
30
*/
31
31
void free_poly (struct term * poly )
32
32
{
33
- if (! poly )
33
+ while ( poly )
34
34
{
35
- return ; // NULL pointer does not need delete
36
- }
37
- else
38
- {
39
- while (!poly -> next )
40
- {
41
- free (poly -> next ); // Deletes next term
42
- }
43
- free (poly ); // delete the current term
35
+ struct term * next = poly -> next ;
36
+ free (poly );
37
+ poly = next ;
44
38
}
45
39
}
46
40
@@ -54,31 +48,19 @@ void free_poly(struct term *poly)
54
48
void create_polynomial (struct term * * poly , int coef , int pow )
55
49
{
56
50
// Creating the polynomial using temporary linked lists
57
- struct term * temp1 , * temp2 ;
58
- temp1 = * poly ; // Contains the null pointer
51
+ struct term * * temp1 = poly ;
59
52
60
- // Initiating first term
61
- if (temp1 == NULL )
53
+ while (* temp1 )
62
54
{
63
- temp2 = (struct term * )malloc (
64
- sizeof (struct term )); // Dynamic node creation
65
- temp2 -> coef = coef ;
66
- temp2 -> pow = pow ;
67
- // Updating the null pointer with the address of the first node of the
68
- // polynomial just created
69
- * poly = temp2 ;
70
- temp2 -> next = NULL ; // Increasing the pointer temp2
71
- }
72
- // Creating the rest of the nodes
73
- else
74
- {
75
- temp2 -> next = (struct term * )malloc (
76
- sizeof (struct term )); // Dynamic node creation
77
- temp2 = temp2 -> next ; // Increasing the pointer temp2
78
- temp2 -> coef = coef ;
79
- temp2 -> pow = pow ;
80
- temp2 -> next = NULL ;
55
+ temp1 = & (* temp1 )-> next ;
81
56
}
57
+
58
+ // Now temp1 reaches to the end of the list
59
+ * temp1 = (struct term * )malloc (
60
+ sizeof (struct term )); // Create the term and linked as the tail
61
+ (* temp1 )-> coef = coef ;
62
+ (* temp1 )-> pow = pow ;
63
+ (* temp1 )-> next = NULL ;
82
64
}
83
65
84
66
/**
0 commit comments