recent

Linked List Program to insert a node at the front,after and End

Linked List Program to insert a node at the front:-

Four Step to insert node before head:-

1. allocate node

2. put in the data

3. Make next of new node as head

 4. move the head to point to the new node

Linked List Program to insert a node after a given node:-

Four Step to insert node after agiven node:-

1. allocate node

2. put in the data

3. Make next of new node as next of prev node

 4. move the next of prev node as new node
 

Linked List Program to insert  a node at the end:-

Four Step to insert node at the end:-

1. allocate node

2. put in the data

3. make new node next=NULL

4. if linked list is empty make new node as head otherwise traverse list till the last node

4. last node next to new node

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

struct node{

int data;
struct node *next;  //structure for a single node...A node have two parts 1->data(int,float,double..etc), 2->pointer to next node
};


int InsertAtFront(struct node **head,int new_data)
{
struct node *new_node;

//Memory allocation for new node
new_node=(struct node *)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=*head;
*head=new_node;

}

int InsertAtMiddle(struct node *first,int new_data)
{
struct node *new_node;

//Memory allocation for new node
new_node=(struct node *)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=first->next;
first->next=new_node;

}

int InsertAtEnd(struct node *head,int new_data)
{
struct node *new_node;

//Memory allocation for new node
new_node=(struct node *)malloc(sizeof(struct node));

new_node->data=new_data;
new_node->next=NULL;

//if Linked List Empty..Make new_node head
if(head==NULL)
{
head=new_node;
}

while(head->next!=NULL)
{
head=head->next;
}
head->next=new_node;

}


void LinkListTraversal(struct node *n)
{
while(n!=0)
{
printf("%d\t",n->data);
n=n->next;
}
printf("\n");
}

main()

{

struct node *head=0; //Link List is empty

//initialize head node

/*  struct node head=(struct node*)malloc(sizeof(struct node))
head->data=2
head->next=NULL
 */

InsertAtFront(&head,6);

LinkListTraversal(head);

InsertAtMiddle(head,8);

LinkListTraversal(head);

InsertAtEnd(head,10);

LinkListTraversal(head);

printf("\n");

InsertAtFront(&head,4);

LinkListTraversal(head);

InsertAtMiddle(head,3);

LinkListTraversal(head);

InsertAtEnd(head,2);

LinkListTraversal(head);
}   
Powered by Blogger.