Write a C program to reverse a linked list in place, without using any extra memory.
Write a C program to reverse a linked list in place, without using any extra memory.
420
21-Apr-2023
Updated on 22-Apr-2023
Aryan Kumar
22-Apr-2023In this program, we define the linked list node structure and a function to create a new linked list node. We then define a function reverseList that takes the head of a linked list as an argument and returns a pointer to the head of the reversed linked list. The function uses three pointers, prev, curr, and next, to keep track of the previous, current, and next nodes in the original linked list. Initially, prev is NULL, curr is the head of the linked list, and next is NULL. We traverse the linked list using a while loop and for each node, we set next to the next node, set the curr->next pointer to prev, set prev to curr, and set curr to next. Finally, we return prev, which is the head of the reversed linked list.
In the main function, we create a linked list and print the original list. We then call the reverseList function to reverse the linked list in place and print the reversed list.