fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct Node {
  4. int data;
  5. struct Node* next;
  6. };
  7. static void reverse(struct Node** head_ref)
  8. {
  9. struct Node* prev = NULL;
  10. struct Node* current = *head_ref;
  11. struct Node* next = NULL;
  12. while (current != NULL) {
  13. next = current->next;
  14. current->next = prev;
  15. prev = current;
  16. current = next;
  17. }
  18. *head_ref = prev;
  19. }
  20. void push(struct Node** head_ref, int new_data)
  21. {
  22. struct Node* new_node
  23. = (struct Node*)malloc(sizeof(struct Node));
  24. new_node->data = new_data;
  25. new_node->next = (*head_ref);
  26. (*head_ref) = new_node;
  27. }
  28. void printList(struct Node* head)
  29. {
  30. struct Node* temp = head;
  31. while (temp != NULL) {
  32. printf("%d ", temp->data);
  33. temp = temp->next;
  34. }
  35. }
  36. int main()
  37. {
  38. struct Node* head = NULL;
  39. push(&head, 4);
  40. push(&head, 3);
  41. push(&head, 2);
  42. push(&head, 1);
  43.  
  44. printf("Given linked list\n");
  45. printList(head);
  46. reverse(&head);
  47. printf("\nReversed linked list \n");
  48. printList(head);
  49. return 0;
  50. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
Given linked list
1 2 3 4 
Reversed linked list 
4 3 2 1