How to Reverse a Linked List in C Programing
Reversing a linked list involves a number of steps before running the program in a Linux system. The first milestone in this task is creating pointers other than the head termed as prevNode as well as curNode. The two pointers help in holding references of the previous node as well as the current node in the C program. It the programmer’s obligation to ensure that the prevNode points the first node, the head points the next node while the curNode directs its pointer towards the second node.
After creating and aligning the pointers, all previous nodes are disconnected. To be precise, the first node in the program is detached from others. That is made possible by making sure that the node is pointing to none. It is then classified as the last node to be used in performing the reverse operation. The third step comes in after the disconnection of nodes. It involves moving the head node to the next node.
The fourth stage in the reverse of linked list process requires the programmer to re-connect the currently existing nodes to the previous nodes. That is followed by pointing of previous node towards current ones. The nodes are also aligned to point the head node created during the first step. That means they should create a sequence of nodes from prevNode to head.
Eventually, the activities in step 3, 4 and 5 are repeated until the head pointer turns null. The order to which nodes are arranged and re-connected represents a reverse order. The last node primarily becomes the first node and vice versa. That means, the head points to prevNode making the original linked list to be reversed.
Finally, the programmer concludes the reversal process by attaining a reversed linked list using c programming.
struct node *reverse(struct node *head { struct node *tail; if (head == NULL || head->link == NULL) { return head; } tail = reverse(tail->link); head->link->link = head; head->link = NULL; return tail; }