/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL || head->next == NULL) return head;
ListNode dummy(0);
dummy.next = head;
head = &dummy;
ListNode *p1 = head, *p2 = head->next;
ListNode *pre;
for(int i = 0; i < m; ++i)
{
pre = p1;
p1 = p1->next;
p2 = p2->next;
}
for(int i = m; i < n; ++i)
{
ListNode *next = p2->next;
p2->next = p1;
p1 = p2;
p2 = next;
}
pre->next->next = p2;
pre->next = p1;
return dummy.next;
}
};
[Leetcode]Reverse Linked List II
最新推荐文章于 2022-10-08 18:10:16 发布