I am writing a program to become familiar with linked lists and when attempting to insert a new link at the end of the list the value is seemingly not stored. I assume it has to do with a local variable not saving to the variable passed into the function.
The function in question:
int insertAtTail(int intBeingAdded, List *userList){
while(userList->next != NULL){
userList = userList->next;
}
List *newLink = (List *)malloc(sizeof(List));
userList->next = newLink;
newLink->next = NULL;
newLink->value = intBeingAdded;
return 1;
}
The entirety of the file:
#include "stdio.h"
#include "stdlib.h"
typedef struct list{
int value;
struct list * next;
} List;
List * initIntegerList(void);
int insertAtHead(int intBeingAdded, List *userList);
int insertAtTail(int intBeingAdded, List *userList);
void printList(List *userList);
int main(void){
List *myList;
myList = initIntegerList();
insertAtHead(2, myList);
insertAtHead(1, myList);
insertAtTail(6, myList);
printList(myList);
freeList(myList);
}
List * initIntegerList(void){
List * listPointer = (List *)malloc(sizeof(List));
if(listPointer != NULL){
listPointer->next = NULL;
return listPointer;
}else{
printf("Memory not available for allocation\n");
return listPointer;
}
}
int insertAtHead(int intBeingAdded, List *userList){
List *previousHead = (List *)malloc(sizeof(List));
if(previousHead != NULL){
previousHead->value = intBeingAdded;
previousHead->next = userList->next;
userList->next = previousHead;
return 1;
}
return 0;
}
int insertAtTail(int intBeingAdded, List *userList){
while(userList->next != NULL){
userList = userList->next;
}
List *newLink = (List *)malloc(sizeof(List));
userList->next = newLink;
newLink->next = NULL;
newLink->value = intBeingAdded;
return 1;
}
void printList(List *userList){
printf("Values in list: ");
List *currentLink = userList;
while(currentLink->next != NULL){
printf(" %d", currentLink->value);
currentLink = currentLink->next;
}
printf("\n");
}
The output I am seeing is only 0,1,2 are stored and the 6 is not making it.