Name : Mhase Sanchit Kishor
Roll No. : 29
Div : E
Experiment No.6
Name of the Experiment:
Reversing a singly linked list
AIM:
1. Modify RLL.c to work for struct Node{char str[10], struct
Node * next}
Equipment / Components required:
VS Code
Pre-requisite:
C Programming Concept
Theory:
Reverse linked list is a linked list created to form a linked list
by reversing the links of the list. The head node of the linked
list will be the last node of the linked list and the last one will
be the head node.
Example
Reverse linked list formed from the above linked list −
85 -> 10 -> 65 -> 32 -> 9 -> NULL
To reverse the given linked list we will use three extra
pointers that will be in the process. The pointers will be
previous, after, current.
We will initialize previous and after to NULL initially and
current to head of the linked list.
After this, we will iterate until we reach the NULL of the
initial (non-reversed linked list). And do the following −
after = current ->
next current ->
next = previous
previous = current
current = after
Now let’s create a program for reversing the linked list. There
can be two ways to create the program, one is iterative and
the other one is recursive.
Program:
// Iterative C program to reverse a linked list
#include <stdio.h>
#include <stdlib.h>
/* Link list node */
struct Node {
int data;
Char str[10];
struct Node* next;
};
/* Function to reverse the linked list */
static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next = NULL;
while (current != NULL) {
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
*head_ref = prev;
}
/* Function to push a node */
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;
}
/* Function to print linked list */
void printList(struct Node* head)
{
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
/* Driver code*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
printf("Given linked list\n");
printList(head);
reverse(&head);
printf("\nReversed Linked list \n");
printList(head);
getchar();
Output:
Given linked list
55 43 20 70
Reversed Linked list
70 20 43 55