当前位置: 代码迷 >> 综合 >> 反转链表II(中等)
  详细解决方案

反转链表II(中等)

热度:14   发布时间:2024-03-08 14:22:35.0

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

说明:

1 ≤ m ≤ n ≤ 链表长度。

struct ListNode
{int val;ListNode *next;ListNode(int x): val(x), next(nullptr) {}
};
class Solution
{
public:ListNode* reverseBetween(ListNode *head, int m, int n){if(n == 1 || !head) return head;ListNode *prev = nullptr;ListNode *curr = head;while(m > 1){prev = curr;curr = curr->next;m--;n--;}ListNode *before = prev;ListNode *after = curr;while(n > 0){ListNode *nextptr = curr->next;curr->next = prev;prev = curr;curr = nextptr;n--;}if(before) before->next = prev;else head = prev;after->next = curr;return head;}
};

 

 

  相关解决方案