首页 > 代码库 > LeetCode Reverse Linked List II
LeetCode Reverse Linked List II
class Solution {public: ListNode *reverseBetween(ListNode *head, int m, int n) { if (head == NULL || n <= m) return head; int offset = n - m; ListNode* cur = head; ListNode* pre = NULL; while (cur != NULL && --m > 0) { pre = cur; cur = cur->next; } ListNode* start = cur; while (cur != NULL && offset-- > 0) { cur = cur->next; } ListNode* end = cur; ListNode* end_next = end->next; end->next = NULL; ListNode* rhead = reverse(start); if (pre == NULL) { head = rhead; } else { pre->next = rhead; } start->next = end_next; return head; } ListNode* reverse(ListNode* head) { ListNode* cur = head; ListNode* pre = NULL; while (cur != NULL) { ListNode* t = cur->next; cur->next = pre; pre = cur; cur = t; } return pre; }};
链表指针还是要小心着点,写着写着把前面想的要注意的地方给漏了
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。