Translate

Wednesday, May 27, 2015

C Programming, using linked list creating multi nodes



#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;
}
void print_list()
{
    struct test_struct *ptr=head;
    while(ptr->next !=NULL){
    printf("%d->", ptr->val);
    ptr=ptr->next;
    }

    if(ptr->next==NULL)
        printf("%d",ptr->val);
}

int main()
{
    int val,i,n;

    printf("How many node you want to create? ");
    scanf("%d", &n);

    for(i=0;i<n;i++){
    scanf("%d", &val);
    add_to_list(val);
    }

    print_list();
    return 0;
}


Output:


Download source code

0 comments:

Post a Comment