0% found this document useful (0 votes)
1 views2 pages

Insert at Position

Uploaded by

roweena.cd23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

Insert at Position

Uploaded by

roweena.cd23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdlib.

h>
#include <stdio.h>

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

struct Node* Start = NULL;

struct Node* getNode(int n)


{
struct Node* p;
p = (struct Node*)malloc(sizeof(struct Node));
if (p == NULL)
{
printf("no memory\n");
return NULL;
}
p->info = n;
p->next = NULL;
return p;
}

void insert_beginning()
{
struct Node* new_node;
int n;

printf("enter the value to be inserted: ");


scanf("%d",&n);

new_node=getNode(n);

if (Start==NULL)
{
Start=new_node;
return;
}
else
{
new_node->next = Start;
Start = new_node;
}
}

void insert_at_any_position(int position, int value) {


struct Node *new_node = getNode(value);
if (new_node == NULL) return;
if (position == 0) {
new_node->next = start;
start = new_node;
return;
}
struct Node *temp = start;
for (int i = 0; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("POSITION OUT OF RANGE\n");
free(new_node);
} else {
new_node->next = temp->next;
temp->next = new_node;
}
}

void traverse()
{
struct Node* p = Start;

if (p == NULL)
{
printf("Empty list\n");
return;
}

printf("List elements: ");


while (p != NULL)
{
printf("%d ", p->info);
p = p->next;
}
printf("\n");
}

int main()
{
insert_beginning();
insert_position(45,2);
traverse();
return 0;
}

void insert_sorted() {
int key;
printf("Enter a value to be inserted in sorted order: ");
scanf("%d", &key);
struct Node* new_node = getNode(key);

// Handle case when the list is empty or the new node should be at the
beginning
if (Start == NULL || Start->info > key) {
new_node->next = Start;
Start = new_node;
} else {
struct Node* p = Start;
// Traverse the list to find the correct insertion point
while (p->next != NULL && p->next->info < key) {
p = p->next;
}
new_node->next = p->next;
p->next = new_node;
}
}

You might also like