fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct ListNode {
  5. int val;
  6. ListNode *next;
  7. ListNode() : val(0), next(nullptr) {}
  8. ListNode(int x) : val(x), next(nullptr) {}
  9. ListNode(int x, ListNode *next) : val(x), next(next) {}
  10. };
  11. void printList(ListNode* head) {
  12. while (head) {
  13. cout << head->val << " ";
  14. head = head->next;
  15. }
  16. cout << endl;
  17. }
  18.  
  19. class Solution {
  20. public:
  21. ListNode* reverseBetween(ListNode* head, int left, int right) {
  22. if (!head || left == right) return head;
  23.  
  24. ListNode dummy(0);
  25. dummy.next = head;
  26. ListNode* prev = &dummy;
  27.  
  28. for (int i = 0; i < left - 1; i++) {
  29. prev = prev->next;
  30. }
  31.  
  32. ListNode* curr = prev->next;
  33. ListNode* next = nullptr;
  34.  
  35. cout << "Initial list before reversing: ";
  36. printList(dummy.next);
  37.  
  38. for (int i = 0; i < right - left; i++) {
  39. next = curr->next;
  40. curr->next = next->next;
  41. next->next = prev->next;
  42. prev->next = next;
  43.  
  44. cout << "After iteration " << i + 1 << ": ";
  45. printList(dummy.next);
  46. }
  47.  
  48. return dummy.next;
  49. }
  50. };
  51.  
  52.  
  53.  
  54. int main() {
  55. ListNode* head = new ListNode(1);
  56. head->next = new ListNode(2);
  57. head->next->next = new ListNode(3);
  58. head->next->next->next = new ListNode(4);
  59. head->next->next->next->next = new ListNode(5);
  60.  
  61. int left = 2, right = 4;
  62. Solution sol;
  63. head = sol.reverseBetween(head, left, right);
  64.  
  65. cout << "Final reversed list: ";
  66. printList(head);
  67.  
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Initial list before reversing: 1 2 3 4 5 
After iteration 1: 1 3 2 4 5 
After iteration 2: 1 4 3 2 5 
Final reversed list: 1 4 3 2 5