博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Reverse Nodes in k-Group
阅读量:6136 次
发布时间:2019-06-21

本文共 1590 字,大约阅读时间需要 5 分钟。

Well, since the head pointer may also be modified, we create a new_head that points to it to facilitate the reverse process.

For the example list 1 -> 2 -> 3 -> 4 -> 5 in the problem statement, it will become 0 -> 1 -> 2 -> 3 -> 4 -> 5 (we init new_head -> val to be 0). Then we set a pointer pre to new_head and another cur to head. Then we insert cur -> next after pre for k - 1 times if the current nodecur has at least k nodes after it (including itself). After reversing one k-group, we update pre to be cur and cur to be pre -> next to reverse the next k-group.

The code is as follows.

1 class Solution {  2 public:  3     ListNode* reverseKGroup(ListNode* head, int k) { 4         if (!hasKNodes(head, k)) return head; 5         ListNode* new_head = new ListNode(0); 6         new_head -> next = head; 7         ListNode* pre = new_head; 8         ListNode* cur = head; 9         while (hasKNodes(cur, k)) {10             for (int i = 0; i < k - 1; i++) {11                 ListNode* temp = pre -> next;12                 pre -> next = cur -> next;13                 cur -> next = cur -> next -> next;14                 pre -> next -> next = temp; 15             }16             pre = cur;17             cur = pre -> next;18         }19         return new_head -> next;20     }21 private:22     bool hasKNodes(ListNode* node, int k) {23         int cnt = 0;24         while (node) {25             cnt++;26             if (cnt >= k) return true;27             node = node -> next;28         }29         return false;30     }31 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4624378.html

你可能感兴趣的文章
Windows Server已可安装Docker,Azure开始支持Mesosphere
查看>>
简洁优雅地实现夜间模式
查看>>
react学习总结
查看>>
微软正式发布PowerShell Core 6.0
查看>>
Amazon发布新的会话管理器
查看>>
InfoQ趋势报告:DevOps 和云计算
查看>>
舍弃Python,为什么知乎选用Go重构推荐系统?
查看>>
在soapui上踩过的坑
查看>>
MySQL的字符集和字符编码笔记
查看>>
ntpd同步时间
查看>>
must implement java.io.Serializable hessian
查看>>
Microsoft Licenses Flash Lite for Windows Mobile Users
查看>>
HDOJ 2020 绝对值排序
查看>>
HDOJ/HDU 2560 Buildings(嗯~水题)
查看>>
Maven编译时跳过Test
查看>>
Spring Boot 整合Spring Security 和Swagger2 遇到的问题小结
查看>>
[20170628]12C ORA-54032.txt
查看>>
除以2
查看>>
高可用集群原理解析
查看>>
Nginx配置URL转向tomcat
查看>>