ShadyBears
ShadyBears

Reputation: 4175

Recursion/linked lists

I can't figure out what is wrong with my insert function.

Basically in the main function I ask a user to input an integer, and it should traverse through the list RECURSIVELY and insert the number in order. Please let me know if you need anything else.

When I print out the list it only prints out 0 twice

In the main:
            **This is looped**
    printf("Enter the value you want to insert: ");
    scanf(" %d", &integer);
    current = insert(&head, integer);
    temp = current;

    while(temp)
    {
        printf("%d\n", temp->num);
        temp = temp->next;
    }


node* insert(node** head, int integer)
{
    node* temp = malloc(sizeof(node));
    node* temp1;
    node* new;

    if(*head == NULL)
    {
        temp->num = integer;
        temp->next = *head;
        *head = temp;
    }
    else if((*head)->num > integer)
    {
        temp = *head;
        temp1 = temp->next; //breaks the link
        temp->next = new;   //creates a new node
        new->num = integer;  //adds int
        new->next = temp1;   //links new node to previously broken node
        *head = temp;
    }

    else
        insert(&((*head)->next), integer);

    return(temp);
}

Thanks alot!

Upvotes: 0

Views: 123

Answers (2)

eyebrowsoffire
eyebrowsoffire

Reputation: 947

while(temp)
{
    printf("%d\n", current->num);
    temp = temp->next;
}

I think you want to be printing out temp->num instead of current->num.

Upvotes: 1

hazzelnuttie
hazzelnuttie

Reputation: 1481

if(*head == NULL)
{
    (*head)->next == temp;
    temp->num = integer;
    temp->next = *head;
    *head = temp;
}

this is wrong and will cause an invalid read as *head is NULL and hence (*head)->next is invalid. It'll read from NULL + offset. Where offset depends upon the definition of your node datatype.

Upvotes: 3

Related Questions