Add element to linked list based on structure - C Data Structure

C examples for Data Structure:Linked List

Description

Add element to linked list based on structure

Demo Code

#include <stdio.h>

struct Node//from   w w w  .  j a v a  2s .c o m
{
    int value;
    struct Node *next;
};

void insertNode(struct Node *newNode, struct Node *existingNode)
{
    newNode->next = existingNode->next;
    existingNode->next = newNode;
}

int main (void)
{

    struct Node n1, n2, nE;
    struct Node *listPointer;

    n1.value = 1;
    n1.next = &n2;

    nE.value = 15;

    n2.value = 20;
    n2.next = (struct Node *) 0;   // mark list end with null pointer

    listPointer = &n1;

    printf("Values in the list before insert of new Node: ");
    while ( listPointer != (struct Node *) 0 )
    {
            printf ("%i ", listPointer->value);
            listPointer = listPointer->next;
    }
    printf("\n");

    insertNode(&nE, &n1);

    listPointer = &n1;

    printf("Values in the list after insert of new Node: ");
    while ( listPointer != (struct Node *) 0 )
    {
        printf ("%i ", listPointer->value);
        listPointer = listPointer->next;
    }
    printf("\n");

    return 0;
}

Result


Related Tutorials