Untitled
unknown
plain_text
a month ago
1.7 kB
5
Indexable
Never
/*Problem Statement : Reverse Linked List II Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.*/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* Reverse(ListNode *head,ListNode *prev){ ListNode* curr = head,*next; while(curr != nullptr){ next = curr->next; curr->next = prev; prev =curr; curr = next; } return prev; } ListNode* reverseBetween(ListNode* head, int left, int right) { ListNode *left_l = head; ListNode* left_1 = head; for (int i = 1;i!=left;i++){ left_l =left_l->next; } for (int i = 1; i!= left-1;i++){ left_1 = left_1->next; } ListNode *right_r = left_l; ListNode *right_1 = left_l; int pos = right - left; if (pos == 0){ return head; } for (int i = left;i != right;i++){ right_r = right_r->next; } for (int i = left; i != right+1;i++){ right_1 = right_1->next; } ListNode *head_l = Reverse(left_l,right_1); left_1->next = head_l; return head; } };
Leave a Comment