I am trying to make a circular linked list in C, but i'm having some trouble. I'm pretty sure it's a pointer issue (I am learning C and pointers are a weakness). here is the code:
#include <stdio.h>
#include <stdlib.h>
#include "cl.h"
nodeptr add_to_end(nodeptr head, int val)
{
if (head == NULL)
{
nodeptr new_node = (nodeptr)malloc(sizeof(node));
new_node->data = val;
new_node->next = NULL;
return new_node;
} else {
head->next = add_to_end(head->next,val);
return head;
}
}
void print_piles(nodeptr nodeHead)
{
if (nodeHead == NULL)
return;
printf("%d\n ",nodeHead->data);
print_piles(nodeHead->next);
}
int main(int argc, char *argv[])
{
nodeptr head = NULL;
nodeptr tail = NULL;
int i = 0;
head = add_to_end(head,i);
i++;
tail = add_to_end(tail,i);
head->next = tail;
i++;
tail = add_to_end(tail,i);
tail->next = head;
printf("%d\n ",head->data);
printf("%d\n ",tail->data);
tail = tail->next;
printf("%d\n ",tail->data);
return 0;
}
and from cl.h:
// create struct for cards in piles
;typedef struct node
{
int data;
struct node *next;
}node, *nodeptr;
the output is:
0
1
0
What I expect to get is:
0
1
2
What do I need to change?