Boomrang
Boomrang

Reputation: 45

C Linkedlist Insertation Not Working and Display Function

I am trying to implement a linked list.But unfortunately it is not working.I have tried changing the code. It doesn't work.The Insertation Function is not working and also the I am not seeing anything when I call the displaylist() function.Help me out please.Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct node {
    int key;
    struct node *next;
} node;

struct node *head, *z, *t;

listinit(void)
{
    head = (struct node *) malloc(sizeof *head);
    z = (struct node *) malloc(sizeof *z);
    head->next = z;
    z->next = z;
}

delnext(struct node *t)
{
   t->next = t->next->next;
}

node *insertafter(int v, struct node *t)
{

    struct node *x;
    x = (struct node *)malloc(sizeof *x);
    x->key = v;
    x->next = t->next;
    t->next = x;
    return x;
};

void displaylist(void)
{
    node *curr = head->next;
    while(curr != z){
        printf("%d -> ", curr->key);
        curr = curr->next;
    }
    printf("\nHappy Coding! :D\n\n");
}

int main(void)
{
    listinit();
    int cmd = 0,val = 0;
    printf("MENU: \n"
           "1. INSERT\n"
           "2. DELETE\n"
           "3. DISPLAY\n");
    printf("OPTION> ");
    scanf("%d",&cmd);
    switch(cmd){
    case 1:
        printf("Please Enter your Key Value >");
        scanf("%d",&val);
        insertafter(val, &head);
        main();
    case 2:
        main();
    case 3:
        displaylist();
        main();
    }
}

Upvotes: 0

Views: 150

Answers (1)

Khaled Mohammad
Khaled Mohammad

Reputation: 183

Your Insertation functions is not working becausue your sending the the location to pointer.Where as the function requires only the pointer.

So change:

insertafter(val, &head);

To This:

insertafter(val, head);

And it will work.

The second problem is your calling the main function everytime again and again which causes the listinit() function to be called and it initializes every pointers.So Remove:

 main();

in the cases.And try using something like this:

do{
 switch(cmd){
case 1:
    printf("Please Enter your Key Value >");
    scanf("%d",&val);
    insertafter(val, &head);
    break;

case 2:
    break;
case 3:
    displaylist();
    break;
    }while(cmd != 0);

That should work now. And avoid recursive calls of main() function because it is a very bad programming practice and leads to problems like this.And use break statements when using switch...case.

Thanks :)

Upvotes: 2

Related Questions