leetcode 之Reverse Nodes in k-Group(22)
Posted 牧马人夏峥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 之Reverse Nodes in k-Group(22)相关的知识,希望对你有一定的参考价值。
这题有点繁琐,在更新指针时很容易出错。
ListNode *reverseKGroup(ListNode *head, int k) { if (head == nullptr || head->next == nullptr || k < 2)return head; ListNode dummy(-1); dummy.next = head; for (ListNode *prev = &dummy, *end = head; end; end = prev->next) { for (int i = 1; i < k; i++) end = end->next; if (end == nullptr)break; prev = reverse(prev, prev->next, end); } return dummy.next; } ListNode *reverse(ListNode *prev, ListNode *begin, ListNode *end) { ListNode *end_next = end->next; for (ListNode *p = begin, *cur = p->next, *pnext = cur->next; cur != end_next; p = cur, cur = pnext, pnext =cur? pnext->next:nullptr) { cur->next = p;//注意指针的指向是一个一个的改变的 } begin->next = end_next; prev->next = end; return begin; }
以上是关于leetcode 之Reverse Nodes in k-Group(22)的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode.25. Reverse Nodes in k-Group
Leetcode 0025. Reverse Nodes in k-Group
LeetCode解题报告—— Reverse Nodes in k-Group && Sudoku Solver
leetcode | Reverse Nodes in k-Group