I've just started DSA recently and this question may seems trivial, but big thanks to those who take it seriously. This is my program:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *link;
};
typedef struct node node;
void printNodes(node* head) {
if(head == NULL)
printf("Linked list is empty");
node *ptr = head;
while(ptr != NULL) {
printf("%d ", ptr->data);
ptr = ptr->link;
}
}
int main() {
node *head = NULL;
head = malloc(sizeof(node));
head->data = 3;
head->link = NULL;
node *current = NULL;
current = malloc(sizeof(node));
current->data = 4;
current->link = NULL;
head->link = current;
current = malloc(sizeof(node));
current->data = 5;
current->link = NULL;
head->link->link = current;
printNodes(head);
}
I have the function below to traverse and print the data of nodes in the linked list:
void printNodes(node *head) {
if(head == NULL)
printf("Linked list is empty");
node *ptr = NULL;
ptr = head;
while(ptr != NULL){
printf("%d ", ptr->data);
ptr = ptr->link;
}
}
I think the code works just fine if we don't use the node* ptr
:
void printNodes(node *head) {
if(head == NULL)
printf("Linked list is empty");
while(head != NULL){
printf("%d ", head->data);
head = head->link;
}
}
Please tell me if my there is any problem in my thought.