Hi all. I'm trying to impliment a simple singly linked list, then allow a user to add a new node. I have mocked up a siimple example to illustrate my point using Linked Lists in C Tutorial - Cprogramming.com
So I have done things similatr to this in C# and Java but not in C. There maybe some parts of this I'm sure some will disagree with in terms of buffers,overflow etc. but it's just the linked list part that I am interested in at the moment, I am only doing it like this because when it works, I will be extracting the working linked list stuff into another program that can deal with its I/O etc.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int x; struct node *next; }; int main() { int x = 0; char input[1]; /* print original linked list with first node(root) */ print(); /* get a users input of a single number */ printf("\nEnter A Number: "); fgets(input,10,stdin); input[1] = '\0'; x = atoi(input); /* use the input from user as the value of the next node */ add(x); /* now print the current linked list in which I want to be root node, then new node */ print(); return 0; } int print() { struct node *root; struct node *node; /* gives root memory of size node */ root = malloc(sizeof(struct node)); /* says next node is node 0 */ root->next = 0; /* assigns variable x of root with value 1 */ root->x = 1; /* assigns node to be root */ if(node != 0) { while(node->next != 0) { printf("%d\n", node->x); node = node->next; } printf("%d\n", node->x); } /* Creates a node at the end of the list */ node->next = malloc(sizeof(struct node)); node = node->next; if(node == 0) { printf("Out of memory"); return 0; } return 0; } int add(int a) { struct node *node; node = malloc(sizeof(struct node)); node->next = 0; node->x = a; return 0; }
I have tried to comment as best I can to demonstarte my intentions and understandings per line of code. The add function needs to add a node of value x that the user has input, and add that to the end of the list - I'm sure that the print function is not doing all its supposed to do - but as i've said my understanding of whats going on here is not exactly complete. Suggestions in terms of next step would be great.
Cheers Guys and Gals.