Originally Posted by
ilans11il
Hi
I'm trying to build a link list with the enclosed code.
could you please help me to create an "add function" to my struct (list) with 2 components (int Y & int X)
Hello there,
If you use a void function, then you will need a pointer of pointer to your struct.
you can try the following:
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int Y;
int X;
struct list *next;
}list;
typedef struct list * LinkedList;
void add (LinkedList* param_linkedListPtr, int param_number)
{
if (*param_linkedListPtr == NULL)
{
*param_linkedListPtr = (LinkedList)malloc(sizeof(struct list));
(*param_linkedListPtr)->X = param_number;
(*param_linkedListPtr)->Y = param_number;
(*param_linkedListPtr)->next = NULL;
}
else
{
LinkedList newList = (LinkedList)malloc(sizeof(list));
newList->X = param_number;
newList->Y = param_number;
newList->next = NULL;
// Add the new element at the end of the list
// So let's go first, to the end of the list
LinkedList tmpList = *param_linkedListPtr;
while (tmpList->next != NULL)
tmpList = tmpList->next;
// Now add the new element at the end of the list
LinkedList *tmpListPtr = &tmpList;
(*tmpListPtr)->next = newList;
}
}
void printList(LinkedList param_LinkedList)
{
LinkedList tmpList = param_LinkedList;
while (tmpList != NULL)
{
printf("%d \t %d \n", tmpList->X, tmpList->Y);
tmpList = tmpList->next;
}
}
int main(int argc, char *argv[])
{
// start testing with an empty list
LinkedList linkedList = NULL;
add(&linkedList, 12);
add(&linkedList, 14);
add(&linkedList, 100);
add(&linkedList, 300);
add(&linkedList, 400);
add(&linkedList, 500);
printList(linkedList);
return 0;
}
Code:
$ gcc -Wall testscript.c -o testscript
$ ./testscript
12 12
14 14
100 100
300 300
400 400
500 500
$
Regards,
Dariyoosh