Q:

C program to create a Linked List and display the elements in the List

belongs to collection: C programs - Linked Lists

0

This program is to create a linked list and display all the elements present in the created list. Linked list is an ordered set of data elements, each containing a link to its successor.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C program to create a Linked List and display the elements in the List - Source code

void main()
{
    struct node
    {
        int n;
        struct node *ptr;
    };
    typedef struct node NODE;
 
    NODE *head, *first, *temp = 0;
    int count = 0;
    int c = 1;
    first = 0;
 
    while (c)
    {
        head  = (NODE *)malloc(sizeof(NODE));
        printf("Enter the data item\n");
        scanf("%d", &head-> n);
        if (first != 0)
        {
            temp->ptr = head;
            temp = head;
        }
        else
        {
            first = temp = head;
        }
        fflush(stdin);
        printf("Do you want to continue(Type 0 or 1)?\n");
        scanf("%d", &c);
 
    }
    temp->ptr = 0;
    /*  reset temp to the beginning */
    temp = first;
    printf("\nStatus of the linked list is\n");
    while (temp != 0)
    {
        printf("%d=>", temp->n);
        count++;
        temp = temp -> ptr;
    }
    printf("NULL\n");
    printf("No. of nodes in the list = %d\n", count);
}

Program Output

Enter the data item
100
Do you want to continue(Type 0 or 1)?
1
Enter the data item
200
Do you want to continue(Type 0 or 1)?
1
Enter the data item
300
Do you want to continue(Type 0 or 1)?
1
Enter the data item
400
Do you want to continue(Type 0 or 1)?
1
Enter the data item
500
Do you want to continue(Type 0 or 1)?
0

Status of the linked list is
100=>200=>300=>400=>500=>NULL
No. of nodes in the list = 5

Program Explanation

1. First a node data structure is declared with a data field as integer variable n and a pointer to the node to access the next node.

2. The malloc function is used to assign memory to a new node of the list. The user is asked to enter the data item. This data value is assigned to info variable (n) of the node.

3. For successive nodes, a temp node is used to assign the pointer and data.

4. If user choose to display the created list, temp variable is reset to first and the list is printed using the while loop. 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to search for an element in the Linked L... >>