Hi this is my first question on stack overflow. I am a software engineering student and I am just starting to understand linked list. I am currently just playing around to get a better understanding for linked list, so please take it easy on me. This is supposed to be a basic concept but is somewhat challenging to understand for me. Is there anyone who can please explain to me why the printList function doesn't traverse through the list for me. I have seen examples that would work but I would really like to understand why my logic isn't working for this function.
My code is down below and I am using gcc to compile my code, not really sure of that makes a difference
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct node{
int data;
struct node* next;
}node;
void printList(struct node *head){
struct node *temp = head;
while(temp->next != NULL){
printf("Here\n");
printf("%d - ",temp->data);
temp = temp->next;
}
printf("\n");
}
//this will create a new node and return a new created node
//data will be set to zero
//next pointer is set to null
struct node createNode(){
struct node temp;
temp.data = 0;
temp.next = NULL;
return temp;
}
//this will add a node to the beginning of the list
//you will need to pass a new head and pass the data you want stored of type int
//this will return a type node
struct node addNode(struct node head,int data){
struct node temp;
struct node ptr;
temp = createNode();
temp.data = data;
if(head.next == NULL){//whent the list is empty
head = temp;
}else{
ptr = head;
while(ptr.next !=NULL){
ptr = *ptr.next;//this will traverse the list until it reaches the end
}
ptr.next = NULL;
head.next = ptr.next;
}
printf("Added: %d\n",temp.data);
return head;
}
int main(){
struct node head = createNode();
struct node *temp = &head;
int userNum;
while(userNum != -1){
printf("Enter a number to add to the linked list: ");
scanf("%d",&userNum);
if(userNum == -1){//this will end the loop
break;
}else{
addNode(*temp,userNum);
}
}
printList(temp);
return 0;
}
My addNode function works but I don't understand why nothing will print out for the printList(). I am using a gcc as my complier if that makes any difference.