inserting in a linked list

//this is a simple program for inserting in a linked lists.
#include<stdio.h>
#include<stdlib.h>

struct link
{
    int data;
    struct link *next;
};


typedef struct link node;
//for changing the name struct link to new name node.

void create_list(node *list);

void show_list(node *list);

node* insert_list(node *list);

int main()
{
    node *head;
    int yes;

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

    create_list(head);

    show_list(head);

    head= insert_list(head);
   
    show_list(head);

    return 0;
}

void create_list(node *list)
//function definition for creating the list
{
    char c;

    scanf("%d%c",&list->data,&c);
//input will terminate when enter is pressed and can be continued by pressing space

    if(c=='\n')
    {
        list->next=NULL;
    }

    else
    {
        list->next=(node*)malloc(sizeof(node));

        create_list(list->next);
//recursion occures
    }

    return;
}

void show_list(node *list)
//function definition for showing the list
{
    while(list)
    {
        if(list==NULL)
            break;

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

        list=list->next;
    }

    printf("\n");
}

node* insert_list(node *list)
//function definition for inserting

{
    int p,found=1,number;
    node *n1;

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

    n1=list;

    printf("Which position do you want to insert:");
    scanf("%d",&p);

    while(list){

        if(p==1)
        {
//for inserting at first
            node *new;

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

            printf("Which value do you want to insert:");
            scanf("%d",&number);
           
            new->data=number;
            new->next=list;
            list=new;

            return list;

        }

        else if(found+1==p&&p!=1)
        {
            node *new;

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

            printf("Which value do you want to insert:");
            scanf("%d",&number);
           
            new->data=number;
            new->next=list->next;
            list->next=new;
           
            return n1;

        }

        found++;
        list=list->next;

          if(list==NULL)
            {
                printf("Data overflow\n");
                return n1;
            }
    }

}

No comments:

Post a Comment

Kruskal Algorithm

Minimum Cost Spanning Tree By Kruskal Algorithm using priority_queue in c++ #include<bits/stdc++.h> using namespace std; typedef p...