0% found this document useful (0 votes)
4 views

java3

The document contains a C program that implements a singly linked list with functionalities to insert nodes at the beginning, end, and specific indices, as well as to count the total number of nodes. It defines a structure for the nodes and includes functions for each operation. The main function runs an infinite loop to allow user interaction for these operations.

Uploaded by

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

java3

The document contains a C program that implements a singly linked list with functionalities to insert nodes at the beginning, end, and specific indices, as well as to count the total number of nodes. It defines a structure for the nodes and includes functions for each operation. The main function runs an infinite loop to allow user interaction for these operations.

Uploaded by

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

#include<stdio.

h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;

void beginsert()
{
struct node *ptr;
int item;
ptr = malloc(sizeof(struct node *));
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");

void display()
{
struct node *ptr;
ptr = head;

printf("\nprinting values . . . . .\n");


while (ptr!=NULL)
{
printf("%d-> ",ptr->data);
ptr = ptr -> next;
}

void main ()
{
int choice =0;
while(1)
{

// Function to insert at end


void insert_at_end(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;

if (head == NULL) {
head = newNode;
return;
}

struct Node* temp = head;


while (temp->next != NULL)
temp = temp->next;

temp->next = newNode;
}

// Function to insert at specific index


void insert_at_index(int value, int index) {
if (index == 1) {
insert_at_head(value);
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;

struct Node* temp = head;


for (int i = 1; i < index - 1 && temp != NULL; i++)
temp = temp->next;

if (temp == NULL) {
printf("Index out of range\n");
free(newNode);
return;
}

newNode->next = temp->next;
temp->next = newNode;
}

// Function to count nodes


int count_nodes() {
int count = 0;
struct Node* temp = head;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}

// Insert at middle

You might also like