C Program to Reverse A Linked List
The programme will turn the linked list that has been provided around and return the new linked list.
A list of links that includes things is known as a linked list. There is a relationship between each link and another link.
Example for a linked list:-
8 -> 29 -> 46 -> 78 -> 97 -> NULL
Reversed linked list:-
A reverse linked list is a linked list made by reversing the links in a regular linked list. The final node in the linked list, which also happens to be the head node, will be the linked list's final node.
Example for a Reversed linked list:-
97 -> 78 -> 46 -> 29 -> 8 -> NULL
We will employ three additional pointers that will be created in the process to reverse the given linked list. The pointers will be prior to, following, and current.
We shall set current to the linked list's head and initialise prior and after to NULL.
We will then repeat this process till we reach the initial (non-reversed linked list's) NULL. Do the following as well.
after = curr ->
next curr ->
next = prev
prev = curr
curr = after
Implementing a Reversed linked list in C:-
#include <stdio.h>
#include <stdlib.h>
//Creating a node in single linked list
struct Node {
int data;
struct Node* next;
};
//Function for reversing the list
static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* curr = *head_ref;
struct Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
*head_ref = prev;
}
//Function for inserting the values into the list
void push(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; } void printList(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } int main() { struct Node* head = NULL; push(&head, 8); push(&head, 29); push(&head, 46); push(&head, 78); push(&head, 97); printf("\nOriginal Linked list is given by: \n"); printList(head); reverse(&head); printf("\nReversed Linked list is given by: \n"); printList(head); getchar(); }
Output:-
![C Program to Reverse A Linked List](https://static.tutorialandexample.com/c/c-program-to-reverse-a-linked-list1.png)