#include <stdio.h>
#include <stdlib.h>
// Node structure for singly linked list
struct Node {
int data; // value stored in the node
struct Node* next; // pointer to the next node
};
// Reverse the linked list in-place
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL; // will become the new head
struct Node* current = head; // pointer to traverse the list
struct Node* next = NULL; // temporary pointer to store next node
while (current != NULL) {
next = current->next; // save next node
current->next = prev; // reverse the link
prev = current; // move prev forward
current = next; // move current forward
}
return prev; // prev is the new head after full reversal
}
// Print the linked list
void printList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d", temp->data);
if (temp->next != NULL) printf(" -> ");
temp = temp->next;
}
printf("\n");
}
// Create a new node
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
int main() {
// Create a sample list: 1 -> 2 -> 3 -> 4 -> 5
struct Node* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
head->next->next->next->next = createNode(5);
printf("Original list:\n");
printList(head);
// Reverse the list
head = reverseList(head);
printf("Reversed list:\n");
printList(head);
return 0;
}
/*
run:
Original list:
1 -> 2 -> 3 -> 4 -> 5
Reversed list:
5 -> 4 -> 3 -> 2 -> 1
*/