fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Node structure
  5. typedef struct Node {
  6. int data;
  7. struct Node* next;
  8. } Node;
  9.  
  10. // Function to create a new node
  11. Node* createNode(int value) {
  12. Node* newNode = (Node*)malloc(sizeof(Node));
  13. newNode->data = value;
  14. newNode->next = NULL;
  15. return newNode;
  16. }
  17.  
  18. // Function to insert at the end
  19. Node* insertEnd(Node* head, int value) {
  20. Node* newNode = createNode(value);
  21. if (!head) return newNode;
  22. Node* temp = head;
  23. while (temp->next) temp = temp->next;
  24. temp->next = newNode;
  25. return head;
  26. }
  27.  
  28. // Function to reverse linked list
  29. Node* reverse(Node* head) {
  30. Node* prev = NULL;
  31. Node* current = head;
  32. Node* next = NULL;
  33. while (current != NULL) {
  34. next = current->next;
  35. current->next = prev;
  36. prev = current;
  37. current = next;
  38. }
  39. return prev;
  40. }
  41.  
  42. // Function to print linked list
  43. void printList(Node* head) {
  44. while (head) {
  45. printf("%d -> ", head->data);
  46. head = head->next;
  47. }
  48. printf("NULL\n");
  49. }
  50.  
  51. int main() {
  52. Node* head = NULL;
  53. head = insertEnd(head, 10);
  54. head = insertEnd(head, 20);
  55. head = insertEnd(head, 30);
  56. head = insertEnd(head, 40);
  57.  
  58. printf("Original List: ");
  59. printList(head);
  60.  
  61. head = reverse(head);
  62.  
  63. printf("Reversed List: ");
  64. printList(head);
  65.  
  66. return 0;
  67. }
  68.  
Success #stdin #stdout 0.01s 5324KB
stdin
45
stdout
Original List: 10 -> 20 -> 30 -> 40 -> NULL
Reversed List: 40 -> 30 -> 20 -> 10 -> NULL