15,346,506 members
See more:
create a linked list having 3 nodes . Then write a code to insert a node at a given position and display the modified linked list.

What I have tried:

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

struct Node{
int data;
struct Node *next;
};

int count=0;

struct Node *newnode;
struct Node *temp;
int pos,i=1;
newnode=(struct Node*)malloc(sizeof(struct Node));
printf("enter position");
scanf("%d",&pos);
if(pos>count){
printf("invalid position");
}
else{
while(i<pos){
temp="temp-">next;
i++;
}
}
printf("enter data");
scanf("%d",&newnode->data);
newnode->next=temp->next;
temp->next=newnode;

}
void display(struct Node *n){
if(n!=NULL){
printf("%d",n->data);
n=n->next;
}
}
int main(){
struct Node *second;
struct Node *third;

second=(struct Node*)malloc(sizeof(struct Node));
third=(struct Node*)malloc(sizeof(struct Node));

second->data=2;
second->next=third;

third->data=3;
third->next=0;
count=3;
return 0;
}
Posted
Updated 10-Apr-21 10:08am

## Solution 1

This seems OK now I have cleaned up the placement of the definitions

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

struct Node
{
int data;
struct Node *next;
};

int count = 0;

struct Node* second;
struct Node* third;

void display(struct Node* n);

int main()
{
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));

second->data = 2;
second->next = third;

third->data = 3;
third->next = 0;

count = 3;

return 0;
}

{
struct Node* newnode;
struct Node* temp = NULL;

int pos = 0;
int i = 1;

newnode = (struct Node*)malloc(sizeof(struct Node));
printf("enter position");
scanf_s("%d", &pos);
if (pos > count)
{
printf("invalid position");
}
else
{

while (i < pos)
{
temp = temp->next;
i++;
}
}
printf("enter data");
scanf_s("%d", &newnode->data);
newnode->next = temp->next;
temp->next = newnode;
}

void display(struct Node* n)
{
if (n != NULL)
{
printf("%d", n->data);
n = n->next;
}
}```