This C Program uses recursive function & reverses the nodes in a linked list and displays the list. A linked list is an ordered set of data elements, each containing a link to its successor. This program makes each data element to link to its predecessor.
Here is the source code of the C program to reverse the nodes and display the linked list. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* Recursive C program to reverse nodes of a linked list and display
* them
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void print_reverse_recursive (struct node *);
void print (struct node *);
void create_new_node (struct node *, int );
//Driver Function
int main ()
{
struct node *head = NULL;
insert_new_node (&head, 1);
insert_new_node (&head, 2);
insert_new_node (&head, 3);
insert_new_node (&head, 4);
printf ("LinkedList : ");
print (head);
printf ("\nLinkedList in reverse order : ");
print_reverse_recursive (head);
printf ("\n");
return 0;
}
//Recursive Reverse
void print_reverse_recursive (struct node *head)
{
if (head == NULL)
{
return;
}
//Recursive call first
print_reverse_recursive (head -> next);
//Print later
printf ("%d ", head -> data);
}
//Print the linkedlist normal
void print (struct node *head)
{
if (head == NULL)
{
return;
}
printf ("%d ", head -> data);
print (head -> next);
}
//New data added in the start
void insert_new_node (struct node ** head_ref, int new_data)
{
struct node * new_node = (struct node *) malloc (sizeof (struct node));
new_node -> data = new_data;
new_node -> next = (*head_ref);
(*head_ref) = new_node;
}
$ cc pgm.c $ a.out LinkedList : 4 3 2 1 LinkedList in reverse order : 1 2 3 4
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at other example programs on Linked List, go to Linked List. If you wish to look at programming examples on all topics, go to C Programming Examples.
Related Posts:
- Practice Computer Science MCQs
- Check Programming Books
- Practice Programming MCQs
- Apply for Computer Science Internship
- Check Computer Science Books