12.20 - 反转链表II
2026/5/8 20:32:32 网站建设 项目流程

1.反转链表

/** * 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* successor = nullptr; ListNode* reverseN(ListNode* head, int n) { if (n == 1) { successor = head->next; return head; } ListNode* last = reverseN(head->next, n - 1); head->next->next = head; head->next = successor; return last; } ListNode* reverseBetween(ListNode* head, int left, int right) { if (left == 1) { return reverseN(head, right); } head->next = reverseBetween(head->next, left - 1, right - 1); return head; } };

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询