Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
4.6k views
in Computer by (69.7k points)

Write a complete program to create a singly linked list. Write functions to do the following operations.

(i) Count the number of nodes 

(ii) Add a new node at the end 

(iii) Reverse the list. 

1 Answer

+1 vote
by (69.2k points)
selected by
 
Best answer

A complete program to create a linked list, counting number of nodes, adding new node at the end and reversing the list is as follows: 

#include< stdio .h>

#include<alloc . h> 

#include<alloc . h>

/* structure containing a data part and link part */

struct node 

{

int data ; 

struct node *link ; 

} ;

void append ( struct node **, int ) ; 

void reverse ( struct node ** ) ; 

void display ( struct node * ) ; 

int count ( struct node * ) ; 

void main( )

{

struct node *p ;

int n;

p = NULL ; /* empty linked list */

printf ( "\nNo. of elements in the linked list = %d", count ( p ) ) ;

printf("\n Enter the element you want to insert");

scanf("%d",&n); 

append (&p,n); 

display ( p ) ;

printf ( "\nNo. of elements in the linked list = %d", count ( p ) ) ; 

reverse ( &p ) ;

printf("\n Elements after reversing the linked list\n");

display (p);

}

/* adds a node at the end of a linked list */ 

void append ( struct node **q, int num ) 

struct node *temp, *r ;

if ( *q == NULL ) /* if the list is empty, create first node */ 

{

temp = malloc ( sizeof ( struct node ) ) ; 

temp -> data = num ; 

temp -> link = NULL ; 

*q = temp ; 

 }

else  

{

}

return(1+count(list->next)); 

}

/* displays the contents of the linked list */

void display ( struct node *q )

{

printf ( "\n" ) ;

/* traverse the entire linked list */

while ( q != NULL )

{

printf ( "%d ", q -> data ) ; 

q = q -> link ;

 } 

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...