diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" index 60088e5977cd92d165bf034060ca8c35106e5a8a..a338879eb64ea74b76b167c6cf2f9800020adad6 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" @@ -71,7 +71,7 @@ ListNode reverse(ListNode a) { 「反转以 `a` 为头结点的链表」其实就是「反转 `a` 到 null 之间的结点」,那么如果让你「反转 `a` 到 `b` 之间的结点」,你会不会? 只要更改函数签名,并把上面的代码中 `null` 改成 `b` 即可: - +[labuladong](https://github.com/labuladong) 提供Java解法代码: ```java /** 反转区间 [a, b) 的元素,注意是左闭右开 */ ListNode reverse(ListNode a, ListNode b) { @@ -88,9 +88,23 @@ ListNode reverse(ListNode a, ListNode b) { return pre; } ``` +[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码: +```C++ +ListNode* reverse(ListNode* begin,ListNode* end) { + ListNode* newHead = nullptr; + ListNode* cur = begin; + while(cur != end) { + ListNode* next = cur->next; + cur->next = newHead; + newHead = cur; + cur = next; + } + return newHead; +} +``` 现在我们迭代实现了反转部分链表的功能,接下来就按照之前的逻辑编写 `reverseKGroup` 函数即可: - +[labuladong](https://github.com/labuladong) 提供Java解法代码: ```java ListNode reverseKGroup(ListNode head, int k) { if (head == null) return null; @@ -109,7 +123,37 @@ ListNode reverseKGroup(ListNode head, int k) { return newHead; } ``` - +[renxiaoyao](https://github.com/tianzhongwei) 提供C++解法代码: +```C++ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + if(!head) return head; + ListNode* begin = head; + ListNode* end = head; + for(int i = 0 ; i < k ; ++i) { + if(!end) + return head; + end = end->next; + } + ListNode* newHead = reverse(begin,end); + begin->next = reverseKGroup(end,k); + return newHead; + } +private: + ListNode* reverse(ListNode* begin,ListNode* end) { + ListNode* newHead = nullptr; + ListNode* cur = begin; + while(cur != end) { + ListNode* next = cur->next; + cur->next = newHead; + newHead = cur; + cur = next; + } + return newHead; + } +}; +``` 解释一下 `for` 循环之后的几句代码,注意 `reverse` 函数是反转区间 `[a, b)`,所以情形是这样的: ![](../pictures/kgroup/6.jpg) @@ -135,4 +179,4 @@ ListNode reverseKGroup(ListNode head, int k) { [下一篇:如何判定括号合法性](../高频面试系列/合法括号判定.md) -[目录](../README.md#目录) \ No newline at end of file +[目录](../README.md#目录)