Reputation: 55
I'm currently working on this simple C program which is intended to create a linked list and display it elements using two functions shto() - to add an alement, and afisho() - to display all the elements of the list. The problem is that the function shto() which is used to add an element at the end of the linked list doesn't work well. When the list is NULL it doesn't add a single element at the list. So I'm guessing that this part of the code isn't correct.
if (koka == NULL)
koka = shtesa;
Actually I've placed these three lines to initialize the list with an element. If you remove these three lines the program won't work.
koka = (node_s *)malloc(sizeof(node_s));
koka->vlera = 0;
koka->next = NULL;
Could anyone help me to make this program work, even if I remove these three lines ? I would really appreciate your help. Thanks in advance!
The code of the program is below.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int vlera;
struct node *next;
} node_s;
node_s *koka, *temp, *shtesa;
node_s* shto (node_s *koka, int vlera)
{
shtesa = (node_s *)malloc(sizeof(node_s));
shtesa->vlera = vlera;
shtesa->next = NULL;
if (koka == NULL)
koka = shtesa;
else
{
temp = koka;
while (temp->next != NULL)
temp = temp->next;
temp->next = shtesa;
}
return koka;
}
void afisho (node_s *koka)
{
if (koka == NULL)
printf("There's no element in the list.\n");
else
{
temp = koka;
do
{
printf("%d\n", temp->vlera);
}
while ((temp = temp->next) != NULL);
}
}
int main ()
{
int i;
koka = (node_s *)malloc(sizeof(node_s));
koka->vlera = 0;
koka->next = NULL;
for (i=1; i<11; i++)
shto (koka, i);
afisho(koka);
return 1;
}
Upvotes: 0
Views: 47
Reputation: 9884
When the list is empty, shto( )
detects in and sets koka
(which is head
, I guess) to the new created element:
if (koka == NULL)
koka = shtesa;
else
...
But within the function koka
is al local variable, so that doesn't affect your global koka
.
As shto()
already returns koka
(the local an maybe modified variable), it should be enough to replace
for (i=1; i<11; i++)
shto (koka, i);
by
for (i=1; i<11; i++)
koka = shto (koka, i);
Upvotes: 1