Click here to Skip to main content
15,892,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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;

void addition(){
struct Node *head;
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{
temp=head;
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 *head;
struct Node *second;
struct Node *third;

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


head->data=1;
head->next=second;


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


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

1 solution

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* head;
struct Node* second;
struct Node* third;

void addition();
void display(struct Node* n);

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

	head->data = 1;
	head->next = second;

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

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

	count = 3;
	display(head);

	addition();
	display(head);

	return 0;
}

void addition()
{
	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
	{
		temp = head;

		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;
	}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900