In the code snippet below the pre-increment operator used in the main
function results in values starting from 2 while the post increment values start from 1 when inserting to the list. I am unable to figure out why.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert_node(int new_data, Node **head_ref) {
Node *node= (Node *)malloc(sizeof (Node));
node->data = new_data;
node->next = *head_ref;
*head_ref = node;
}
void display(Node *head) {
Node *traverse = head;
while (traverse->next != NULL) {
printf("\ndata=%d", traverse->data);
traverse = traverse->next;
}
}
void main() {
Node *pdata;
Node *list_head = NULL;
int i = 0;
while (i <= 10)
insert_node(++i, &list_head);
display(list_head);
}
First, you need to understand how pre and post increment work.
Pre-Increment: increment the value of a variable before using it in an expression.
Example:
int i = 0;
// first increment value of i by 1 and then print it
print("%d", ++i); // output: 1
print("%d", i); // output: 1
Post-Increment: increment the value of the variable after executing the expression completely, in which post-increment is used.
Example:
int i = 0;
// first use the value of i in print() and after executing
// the print(), increment value of i
print("%d", i++); // output: 0
print("%d", i); // output: 1
Now it depends on you which one you have to use.
Second, as far as I understand there is a logical error in this function
void display(Node* head)
{
Node* traverse = head;
while (traverse->next != NULL)
{
printf("\ndata=%d", traverse->data);
traverse = traverse->next;
}
}
The while loop condition should be
while (traverse != NULL)
I hope, it will answer your question.