fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Definition for singly-linked list.
  5. struct ListNode {
  6. int val;
  7. ListNode* next;
  8. ListNode(int x) : val(x), next(nullptr) {}
  9. };
  10.  
  11. class Solution {
  12. public:
  13. ListNode* reverseList(ListNode* cur, ListNode* prev = nullptr) {
  14. if (cur == nullptr) return prev;
  15. ListNode* nxt = cur->next;
  16. cur->next = prev;
  17. return reverseList(nxt, cur);
  18. }
  19. };
  20.  
  21. // Helper function to print the linked list
  22. void printList(ListNode* head) {
  23. while (head != nullptr) {
  24. cout << head->val << " -> ";
  25. head = head->next;
  26. }
  27. cout << "NULL" << endl;
  28. }
  29.  
  30. // Helper function to create a linked list from an array
  31. ListNode* createList(int arr[], int n) {
  32. if (n == 0) return nullptr;
  33. ListNode* head = new ListNode(arr[0]);
  34. ListNode* current = head;
  35. for (int i = 1; i < n; ++i) {
  36. current->next = new ListNode(arr[i]);
  37. current = current->next;
  38. }
  39. return head;
  40. }
  41.  
  42. int main() {
  43. int arr[] = {1, 2, 3, 4, 5};
  44. int n = sizeof(arr) / sizeof(arr[0]);
  45.  
  46. // Create the linked list
  47. ListNode* head = createList(arr, n);
  48.  
  49. cout << "Original list: ";
  50. printList(head);
  51.  
  52. // Reverse the list
  53. Solution sol;
  54. ListNode* reversed = sol.reverseList(head);
  55.  
  56. cout << "Reversed list: ";
  57. printList(reversed);
  58.  
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Original list: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Reversed list: 5 -> 4 -> 3 -> 2 -> 1 -> NULL