Translate

Wednesday, May 27, 2015

C programming, using linked list creating a node






#include<stdio.h>
#include<conio.h>

struct test_struct
{
    int val;
    struct test_struct *next;
};
struct test_struct *head=NULL;
struct test_struct *curr=NULL;

struct test_struct* create_list(int val)
{
    struct test_struct *ptr=(struct test_struct*) malloc(sizeof(struct test_struct));
    if(ptr==NULL)
    {
        printf("Node creating failed\n");
        return;
    }
    ptr->val=val;
    ptr->next=NULL;
    head=curr=ptr;
    return ptr;

}

struct test_struct* add_to_list(int val)
{
    if(head==NULL)
    {
        return(create_list(val));
    }
    struct test_struct *ptr=( struct test_struct*) malloc(sizeof(struct test_struct));
    if(ptr==NULL)
    {
        printf("node creation failed");
        return;
    }
    ptr->val=val;
    ptr->next=NULL;
    curr->next=ptr;
    curr=ptr;
    return ptr;
}

int main()
{
    struct test_struct *a;
    int val;

    scanf("%d", &val);
    a=add_to_list(val);

    while (a->next != NULL){

        printf("%d", a->val);
        a->next = a->next->next;
    }

        printf("%d", a->val);
        return 0;


}

Download source code

0 comments:

Post a Comment