i can't seem to understand the logic behind linked lists :|
Ok i've made my code really simplistic to tackle the problem i'm having currently of understanding how linked lists work. I only know what happens until a new node is added (i.e. 1) but i can't seem to understand what happens AFTER that i.e if there are more than 1 nodes. So i've highlighted the bits where i exactly can't understand. Hopefully someone can explain it step by step.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct charNode
{
char petName[12];
struct charNode *next;
};
typedef struct charNode charNode;
void addElement(charNode **start, char *petName);
void printList(charNode *start);
charNode* newNode(char *petName);
void getString(charNode *start);
int main()
{
charNode *start = NULL;
getString(start);
return 0;
}
void getString(charNode *start)
{
addElement(&start, "(1)Cat");
addElement(&start, "(2)Dog");
addElement(&start, "(3)Horse");
printList(start);
}
void addElement(charNode **start, char *petName)
{
charNode *temp,*prev, *loc;
int i;
temp = newNode(petName);
if (*start == NULL)
{
*start = temp;
}
else
{
loc = *start;
prev = NULL;
for (i=0; loc != NULL; i++)
{
printf("%d", i);
printf(" %s ", loc->petName);
prev = loc;
loc = loc->next;
}
printf("\n");
printf("\n");
temp->next = loc;
prev->next = temp;
}
}
charNode* newNode(char *petName)
{
charNode *temp;
temp = (charNode *) malloc(sizeof(charNode));
if (temp == NULL)
{
printf("WARNING - Memory allocation error\n");
exit(EXIT_FAILURE);
}
strcpy(temp->petName, petName);
temp->next = NULL;
return temp;
}
void printList(charNode *start)
{
while (start != NULL)
{
printf("%s\n", start->petName);
start = start->next;
}
}