Insertion in Link List
Insertion in Link List
Start
A B C
P->info= item
P- >next= start
d
Start= P
Algorithm : Insert_begin(start, item)
A B C
D
Algorithm for Insertion at the end
Algorithm : Insert_end(start, item)
1. Create a new node ptr[Check for overflow]
If(ptr==NULL) then print overflow and exit.
2. Set ptr ->info=item
3. Set ptr->next=NULL
4. If start==NULL then Start=ptr and exit
5. Set loc= start
6. Repeat step 7 Untill loc->next!=NULL
7. Set loc=loc->next
8. Set loc->next=ptr
.
void append( )// Insertion at the end
{
struct node* ptr;
ptr = ((struct node*) malloc (sizeof(struct node)));
printf(“ Enter Node Data: ”);
scanf(“%d”, &ptr -> data);
ptr -> next = NULL;
if(start = = NULL)
{
start = ptr;
}
else
{
struct node* loc;
loc = start;
while( loc -> next != NULL)
{
loc = loc -> next;
}
loc -> next = ptr;
}
}
Insertion after a Specific position
Element x is inserted between the third an fourth elements in an array
X0 X0 X0
X1 X1 X1
X2 X2 X2
X3 x
X4 X3 X3
X5 X4 X4
X6 X5 X5
X6 X6
Insertion after a Specific position
Inserting an item x into a list after a location p
p
list X0 X1 X2 X3 X4 X5 X6 null
list X0 X1 X2 X3 X4 X5 X6 null
q x
Insertion after a Specific position
Inserting an item x into a list after a location LOC
Algorithm : Insert_position(start, loc, item)
1. Create a new node[Check for overflow]
If(ptr==NULL) then print overflow and exit.
2. Set ptr ->info=item
3. If start==NULL then Start=ptr,ptr->next=NULL and exit
4. Initialize counter i and pointer temp
i=0,temp=start
5. Repeat Until i <loc and list exist
Set temp=temp->next,
Set i=i+1
6. Set ptr->next=temp->next
7. Set temp->next=ptr
8. Exit
void addafter ( )
{
struct node *temp, *p;
int loc, len, i = 1;
printf(“Enter Location: ”);
scanf(“%d”, &loc);
len = length( );
if(loc > len)
{
printf(“Invalid Location”);
printf(“Currently list is having %d nodes”, len);
}
else
{
temp = start;
while(i < loc)
{
temp = temp -> next;
i++;
}
ptr = (struct node*)malloc(sizeof(struct node)));
printf(“Enter node data: ”);
scanf(“%d”, &ptr -> data);
ptr -> next = NULL;
ptr -> next = temp-> next; //Right Connection
temp -> next = ptr; // Left Connection
}
}
Length of the Linked List
int length ( )
{
int count = 0;
struct node* temp; temp = start;
while( temp!= NULL)
{
count ++;
temp = temp -> next;
}
return count;
}
Thank
You