Hello Friends,
Today i am going to explain you How to insert Newnode Node at Last Position of Linked List.
Function For Insert at Last:
insert_at_last()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter Number you want to add at last position of linked list:");
scanf("%d",&newnode->data);
newnode->next=NULL;
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
temp=temp->next;
}
Full Program :
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *newnode,*head,*temp;
void create()
{int num,i;
printf("\nHow many nodes you want to create:");
scanf("%d",&num);
for(i=0; i<num; i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter Data:");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(head==NULL)
{head=temp=newnode;}
else
{temp->next=newnode;
temp=temp->next;
}}}
insert_at_last()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter Number you want to add at last position of linked list:");
scanf("%d",&newnode->data);
newnode->next=NULL;
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
temp=temp->next;
}
void display()
{
struct node *p;
p=head;
while(p->next!=NULL)
{
printf("%d->", p->data);
p=p->next;
}
printf("%d->",p->data);
}
void main()
{
create();
display();
insert_at_last();
display();
getch();
}
Output:
No comments:
Post a Comment