-1

I have been encountering so many codes in polynomial which creates the polynomial using double pointers as arguments and in the following code I have a question that why a new node is created for the next pointer of type Node. If possible can someone please explain me the working of this code.

struct Node 
{ 
    int coeff; 
    int pow; 
    struct Node *next; 
}; 

// Function to create new node 
void create_node(int x, int y, struct Node **temp) 
{ 
    struct Node *r, *z; 
    z = *temp; 
    if(z == NULL) 
    { 
        r =(struct Node*)malloc(sizeof(struct Node)); 
        r->coeff = x; 
        r->pow = y; 
        *temp = r; 
        r->next = (struct Node*)malloc(sizeof(struct Node)); 
        r = r->next; 
        r->next = NULL; 
    } 
    else
    { 
        r->coeff = x; 
        r->pow = y; 
        r->next = (struct Node*)malloc(sizeof(struct Node)); 
        r = r->next; 
        r->next = NULL; 
    } 
} 

calling of the function is done in this way from main:

    struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL; 

        // Create first list of 5x^2 + 4x^1 + 2x^0 
        create_node(5,2,&poly1); 
        create_node(4,1,&poly1); 
        create_node(2,0,&poly1); 
// Create second list of 5x^1 + 5x^0 
    create_node(5,1,&poly2); 
    create_node(5,0,&poly2); 
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Ayush Mishra
  • 49
  • 1
  • 7

2 Answers2

2

why a new node is created for the next pointer of type Node.

Its just because the author felt like doing it that way. The code could also be written like that. But the shown code has undefined behaviour since r is dereferenced in the else-part without being initialized first and most likely is an invalid pointer value.

One would have to traverse from *temp (z - please pic better names) through all existing nodes and then append a new node:

void create_node(int x, int y, struct Node **temp)
{
    struct Node *r, *z;
    z = *temp;
    if (!z)
    {
        r = malloc(sizeof(struct Node)); // do not cast the result of malloc()!
        r->coeff = x;
        r->pow = y;
        r->next = 0;
        *temp = r;
    }
    else
    {
        r = z;
        while (r->next)
            r = r->next;

        r->next = malloc(sizeof(struct Node));
        r = r->next;
        r->coeff = x;
        r->pow = y;
        r->next = 0;
    }
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43
0

There is no need for special cases; instead, just use the pointer-to-pointer:


void create_node(int x, int y, struct Node **temp) 
{ 
    struct Node *this;
    this = malloc(sizeof *this);
    this->next = *temp;    // steal the parent's pointer.
    this->coeff = x;    
    this->pow = y;    
    *temp = this;          // and put ourself in front of it
} 

Do note that if the original list is empty, *temp will be NULL, and this->next will be set to NULL, too. (which is what we want)

wildplasser
  • 43,142
  • 8
  • 66
  • 109