I am not getting the else part in create_node() function..
As you can see in the else part ,memory block is allocated for r and coeff and power are assigned...but when did they assign r node to the last of linkedlist.. when did they traverse to end of linked list
I mean how is it getting assigned at the last of linked list.
#include <bits/stdc++.h>
using namespace std;
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;
}
}
// Display Linked list
void show(struct Node* node)
{
while (node->next != NULL) {
printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if (node->coeff >= 0) {
if (node->next != NULL)
printf("+");
}
}
}
// Driver code
int 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, 2, &poly2);
create_node(-5, 0, &poly2);
printf("1st Number: ");
show(poly1);
printf("\n2nd Number: ");
show(poly2);
return 0;
}
Am I the only one who thinks that create_node() function should be more like this than the above code?
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;
r->next=NULL;
*temp = r;
}
else {
r = (struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
r->next=NULL;
while(z->next!=NULL)
{
z=z->next;
}
z->next=r;
}
}
I really want to know how is it producing the right output, even without assigning newnode to last of linked list
create_nodetakes a node and appends to it. Theelsebranch is for when the node passed in astempis not the last also called tail (or rather that it exists as per this implementation).