LeetCode Reverse Nodes in k-Group
来源:互联网 发布:快速域名网站备案 编辑:程序博客网 时间:2024/06/15 04:30
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
class Solution {public:ListNode *reverseKGroup(ListNode *head, int k) {if (head == NULL || head->next == NULL || k <= 1)return head;ListNode *plast = head;ListNode *pslow = head;ListNode *pmid = head->next;ListNode *pfast = head->next;bool firstK = true;while (pfast != NULL) {//每次开始时,先检测下一组是否有k个节点,没有就结束循环。ListNode *ptemp = pslow; for (int i = 0; i < k - 1; i++) {ptemp = ptemp->next; if (ptemp == NULL)break;}if (ptemp == NULL) //结束整个大循环break;ptemp = pslow; //临时保存每组k个节点的第一个节点//节点逆序,循环结束时,pslow 指向本组k个节点的最后一个(新链的第一个节点),// pmid 和 pfast 指向下一组的第一个节点for (int i = 0; i < k - 1; i++) {pfast = pmid->next;pmid->next = pslow;pslow = pmid;pmid = pfast;}//如果是第一组k个节点,则更新 head,否则让上一组逆序后的最后一个节点 链上本组逆序后的首节点if (firstK) {head = pslow;firstK = false;}else {plast->next = pslow;}//更新pslow,使其指向 下一组k个节点的第一个节点,让 pmid 和 pfast指向第二个节点 或 NULLpslow = pmid; if (pfast != NULL) {pfast = pfast->next;pmid = pfast;}plast = ptemp; // 更新plast, 使其指向本组 k个节点逆序后的最后一个节点}if (plast != pslow) //将最后一组接上plast->next = pslow;return head;}};
0 0
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- LeetCode | Reverse Nodes in k-Group
- 【leetcode】Reverse Nodes in k-Group
- Leetcode: Reverse Nodes in k-Group
- leetcode Reverse Nodes in k-Group
- [LeetCode] Reverse Nodes in k-Group
- LeetCode题解: Reverse Nodes in k-Group
- 【Leetcode】Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- [Leetcode] Reverse Nodes in k-Group (Java)
- LeetCode(25)Reverse Nodes in K-Group
- 《精通CSS(第2版)》读书笔记2
- C/C++中的extern关键字详解
- 关于尝试spinner中遇到的小问题
- 菜鸟自己实现一个多线程操作对象中的同一个数据
- Activity生命周期
- LeetCode Reverse Nodes in k-Group
- At.js的使用
- 阿里巴巴集团2014秋季校园招聘笔试题
- ubuntu中ftp服务器的安装和设置
- LeetCode OJ算法题(六十五):Add Binary
- Android开发环境与文件目录介绍
- Eclipse + Python 的安装与配置流程
- ArcGIS Engine问答:为什么地理数据库中不能产生同名要素类
- LaTeX编译排错