0% found this document useful (0 votes)
7 views2 pages

Inserting in Linked List at Position

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Inserting in Linked List at Position

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

// Program for Singly Linked List Insertion at a given position in

C
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *next;
};
// current size of Linked List
int size = 0;
int pos,ele;

void insert (struct Node **head, int data)


{
struct Node *new_node = (struct Node *) malloc (sizeof (struct
Node));

new_node->data = data;
new_node->next = *head;
*head = new_node;
size++;
}

// method to insert at a given position


void insertPosition (int pos, int data, struct Node **head)
{

struct Node *new_node = (struct Node *) malloc (sizeof (struct


Node));
new_node->data = data;
new_node->next = NULL;

// Invalid positions
if (pos < 1 || pos > size + 1)
printf ("Invalid\n");

// inserting first node


else if (pos == 1)
{
new_node->next = *head;
*head = new_node;
size++;
}

else
{
struct Node *temp = *head;

// traverse till the current (pos-1)th node


while (--pos > 1)
{
temp = temp->next;
}
new_node->next = temp->next;
temp->next = new_node;
size++;
}
}

void display (struct Node *node)


{

printf ("Linked List : ");

// as linked list will end when Node is Null


while (node != NULL)
{
printf ("%d->", node->data);
node = node->next;
}
printf ("null\n");
}

void main ()
{
struct Node *head = NULL;
clrscr();
printf("existing linked list");
insert (&head, 70);
insert (&head, 60);
insert (&head, 40);
insert (&head, 30);
insert (&head, 10);
display (head);
printf("enter the position at which element is to be inserted");
scanf("%d",&pos);
printf("enter the element to be inserted");
scanf("%d",&ele);
insertPosition (pos,ele,&head);
display (head);
getch();
}

You might also like