Solved programming problem

Insert Linked List Where every value insert at the last Index in C.

Source code

#include <stdio.h>

struct student

{

    int data;

    int *next;

};

typedef struct student node;

int print(node *i)

{

    printf("Your Array: 
");

    while(i!=NULL)  ///print all element until NULL

    {

        printf("%d ",i->data);

        i=i->next;

    }printf("
");

    return;

}

int main()

{

    node *start,*last;

    int flag,i;

    start =NULL;

    do   ///while user press 1,this loop run infinitely

    {

        printf("Do you Want to Create a New Node?(1/0)
");

        scanf("%d",&flag);

        if(flag !=1) break;

        /// replace in first

        temp = (node *)malloc(sizeof(node));

        printf("Please Enter First Value: ");

        scanf("%d",&temp->data);

        temp->next = NULL; ///save the data next to NULL

        if(start==NULL)

        {

            start = temp;

        }

        else

        {

           /*for insert last*/

            last = start;

            while(last->next != NULL)

            {

               last = last->next;  /// save the last index

            }

            last ->next = temp; ///replace new value to last index

        }

    }

    while(flag==1);

    print(start);

    return 0;

}

Output

Do you Want to Create a New Node?(1/0)

1

Please Enter First Value:

5

Do you Want to Create a New Node?(1/0)

1

Please Enter First Value:

9

Do you Want to Create a New Node?(1/0)

1

Please Enter First Value:

4

Do you Want to Create a New Node?(1/0)

0

Your Array:

5 9 4

Join the discussion

Add your comment