0% found this document useful (0 votes)
18 views

Singly Linked List

This document contains code for inserting a node at the beginning and middle of a linked list. The insert_at_beg function allocates memory for a new node, gets user input for the node data, and adds the node to the start of the list by making its next pointer point to the original start node or NULL if the list was empty. The insert_mid function similarly allocates a new node and gets its data, but finds the node before the desired insertion position by iterating through the list with a temp pointer, then links the new node between the node temp is pointing to and its next node.

Uploaded by

achaparala4499
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Singly Linked List

This document contains code for inserting a node at the beginning and middle of a linked list. The insert_at_beg function allocates memory for a new node, gets user input for the node data, and adds the node to the start of the list by making its next pointer point to the original start node or NULL if the list was empty. The insert_mid function similarly allocates a new node and gets its data, but finds the node before the desired insertion position by iterating through the list with a temp pointer, then links the new node between the node temp is pointing to and its next node.

Uploaded by

achaparala4499
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

void insert_at_beg()

{
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
if(new_node == NULL)
printf("nFailed to Allocate Memory");
printf("nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
new_node->next=start;
start=new_node;
}
}

void insert_mid()
{
int pos,i;
struct node *new_node,*current,*temp,*temp1;
new_node=(struct node *)malloc(sizeof(struct node));
printf("nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
st :
printf("nEnter the position : ");
scanf("%d",&pos);
if(pos>=(length()+1))
{
printf("nError : pos > length ");
goto st;
}

if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
temp = start;
for(i=1;i< pos-1;i++)
{
temp = temp->next;
}
temp1=temp->next;
temp->next = new_node;
new_node->next=temp1;
}
}

You might also like