How to Reverse Linked List Using Iteration in C programming

CWC
3 Min Read

Lists in C language are linked using pointers ,each pointer refer to a case and each case contain another pointer that refer to the next case, for a linked list with N nodes reversing the lists means that we will reverse the sequence of nodes and each case will point to the precedent instead of the next one, to reverse with the iteration way we will use the previous , current and next pointer .we will create the “reverse_list” function with the type struct because it will return a struct and as arguments it will take the linked struct and return the head pointer of the reversed one.

In the function we will start by declaring the three nodes :previous, next and actual one as structures then we will initialize the previous to NULL and the next to the head of the original struct given in parameters of the function, then we should use a loop to browse the original linked list, using “while” we will need a stop condition and in this case we won’t stop unless if the actual element equal NULL which means that we have browsed the whole list, inside the loop we will change the value of the pointers at each iteration by affecting the next that point to the head to the next of the actual new list, and next of the current list to previous of the list which pointed ti NULL, also we need to change the previous to the current and the current to the next pointer to ensure that the new list will be browsed in the opposite direction of the original one .After the exit from the loop we need to return a value

The value is the pointer to our new list, exactly previous pointer because after the loop, now it point to the new Linked List .of course we will need also a function that reeds our list and that should be declared also in another bloc and it will use our list as an argument.

struct node
{
char value;
struct node *link;
};
node * reverse(node *head)
{
struct node *a = head
*b = NULL,
*c = null;
while (p != NULL)
{
c = b;
b = a;
a = a->link;
b->link = c;
}
b = head;
return b;
}
Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version