-
singly linked list
I am building a phone book and require the use of pointers to do so. My issue is there a way to add nodes from user input without hard lining the code myself in?
Code:
struct pb
{
int* data;
char* first;
char* last;
char* phone;
struct pb* next;
};
pb* e1 = NULL;
pb* e2 = NULL;
pb* e3 = NULL;
.........
e1 = malloc(sizeof(struct pb));
e2 = malloc(sizeof(struct pb));
e3 = malloc(sizeof(struct pb));
..........
e1->data = 1;
e1->next = e2;
e2->data = 2;
e2->next = e3;
e3->data = 3;
e3->next = e4;
.......
i am sure there is an easier and simplier way to do this, but i can not figure it out. Please advise
-
You keep a node that is the head of the list. Then you use a pointer as an iterator to traverse the list to the end:
Code:
struct pb *iterator;
struct pb *new_node = malloc(sizeof(struct pb));
for(iterator = head;iterator->next != NULL;iterator = iterator->next);
/* now after that for iterator is the last element so we can insert */
iterator->next = new_node;
new_node->next = NULL;
-
thank you very much. I was thinking of a while loop but could not quite get it right