TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Insert at nth Position in Linked List
Kaushik S
Nov 28
2015
Code
2.6
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef
struct
node
{
int
data;
struct
node* next;
}node;
struct
node* head;
void
insert(
int
x)
{
struct
node* temp=head;
temp=(node*)malloc(
sizeof
(
struct
node));
temp->data=x;
if
(head==NULL)
{
temp->next=NULL;
head=temp;
}
else
{
struct
node* temp2=NULL;
temp2=(node *)malloc(
sizeof
(
struct
node));
temp=head;
while
(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=temp2;
temp2->data=x;
temp2->next=NULL;
}
}
void
print()
{
struct
node* temp=head;
while
(temp!=NULL)
{
printf(
"%d"
,temp->data);
printf(
":"
);
temp=temp->next;
}
}
int
count()
{
struct
node* temp=NULL;
int
count=0;
while
(temp!=NULL)
{
count++;
temp=temp->next;
}
return
count;
}
void
insertAtNth(
int
value,
int
pos)
{
struct
node* temp=NULL;
temp=(node*)malloc(
sizeof
(
struct
node));
if
(pos==1)
{
temp->data=value;
temp->next=head;
head=temp;
return
;
}
else
{
struct
node* temp2=head;
struct
node* temp3=NULL;
int
i=0;
for
(i=1;i<pos-1;i++)
{
//temp=temp1;
temp2=temp2->next;
temp3=temp2->next;
}
temp2->next=temp;
temp->data=value;
temp->next=temp3;
//temp->next=temp2->next;
}
printf(
" After insertion "
);
print();
}
void
main()
{
insert(4);
insert(8);
insert(12);
insert(16);
insert(20);
print();
insertAtNth(24,1);
insertAtNth(45,3);
getch();
}
C
Datastructures
Linked List