Today we are starting linked . and the simplest program of linked is inserting element in a linked list . there can be various insertion elements anywhere in linked list and can also create new one . i am discussing three methods
1> if you want to add element at end of linked list
2> you wanted to add the element at first position means opposite to first one .
3> suppose you are giving the pointer of previous node where you want to insert element
for this i used three different functions respectively
1> append ()
2> push()
3> insert_after()
#include<stdio.h>
struct node
{
int data;
struct node* next;
};
void main()
{
struct node* head = NULL;
append(&head,7); /*append is a function that will add the node at end */
append(&head,6);
push(&head,9); /*push will add the element on head */
insert_after(head->next->next, 43);
push(&head, 64);
output(head);
}
void append(struct node** m, int value) /* m is a pointer that is storing the address of head */
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data=value;
temp->next= NULL;
struct node *current = *m ; /* (*m) means that value at the head as m was storing the address of head )*/
/*current has same value now that of head */
if(*m == NULL)
{
*m = temp;
}
else
{
while(current ->next!= NULL)
{
current=current->next;
}
current->next=temp;
}
}
void push(struct node **m , int value )
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data=value;
temp->next = *m; /* (*m) means that value at the head as m was storing the address of head )*/
*m= temp; /*head will change by this */
}
void insert_after(struct node *prev_node,int value)
{
if (prev_node== NULL)
{
printf("previous node can't be null");
return;
}
else
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data=value;
temp->next = prev_node->next ;
prev_node->next = temp;
}
}
void output(struct node* current)
{
while(current!=NULL)
{
printf("%d\n",current->data);
current=current->next;
}
}
the following picture will explain the pointers used in append function
and this picture will explain the insert_after function
No comments:
Post a Comment