nikunjsoni

92

Mar 19th, 2021
62
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.     ListNode* reverseBetween(ListNode* head, int left, int right) {
  14.         ListNode *start, *pre_ptr, *next_ptr;
  15.         ListNode *dummy = new ListNode(0, head);
  16.         ListNode *curr=dummy;
  17.         for(int i=0; i<left-1; i++){
  18.             curr = curr->next;
  19.         }
  20.         pre_ptr = curr;
  21.         start = curr->next;
  22.         next_ptr = start->next;
  23.        
  24.         for(int i=0; i<right-left; i++){
  25.             start->next = next_ptr->next;
  26.             next_ptr->next = pre_ptr->next;
  27.             pre_ptr->next = next_ptr;
  28.             next_ptr = start->next;
  29.         }
  30.         return dummy->next;
  31.     }
  32. };
RAW Paste Data