LeetCode(25)--Reverse Nodes in k-Group
来源:互联网 发布:如何利用网络做直销 编辑:程序博客网 时间:2024/06/16 17:48
转载自博客
题目要求对链表中的元素按K个一组,反序后,形成新的链表。对于最后不满K个元素,保持原来的顺序输出。所以本题可以按如下方法解:
1、建立空的新链表list1.
2、如果原链表剩余元素个数不小于K个,则取K个元素,采用头插法构建反序的临时链表,插入list1的尾部。
3、如果链表剩余元素个数小于K个,则将剩余的链表插入到list1的尾部。
实现代码如下:
class Solution {public: ListNode* reverseKGroup(ListNode* head, int k) { if (head == nullptr) return nullptr; int count = 0; ListNode* res=NULL; ListNode tmpHead(-1); ListNode *tail = &tmpHead; ListNode*p = head; //计算链表的长度 while (head) { head = head->next; count++; } //待反序的链表数 int m = count / k; if (m == 0)return p; while (m) { //每k个的头部pHead,再将pHead连接到上一k个 ListNode *pHead = NULL; for (int i = 0; i < k; i++) { ListNode* tmpP = p; p = p->next; pHead = addHead(pHead, tmpP); } if (m ==count/k)res = pHead; //上一个的tail尾部连接到新的头部 tail->next = pHead; //找到每k个反序后的最后一个tail while (tail->next) { tail = tail->next; } m--; } tail->next = p; return res; } ListNode* addHead(ListNode*head, ListNode* Node) { Node->next = head; return Node; }};
阅读全文
0 0
- LeetCode(25)Reverse Nodes in K-Group
- [leetcode 25]Reverse Nodes in k-Group
- [leetcode #25]Reverse Nodes in k-Group
- leetcode 25 Reverse Nodes in k-Group
- Leetcode 25 Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- LeetCode 25: Reverse Nodes in k-Group
- leetcode 25 -- Reverse Nodes in k-Group
- leetcode 25:Reverse Nodes in k-Group
- leetcode 25: Reverse Nodes in k-Group
- [Leetcode 25] Reverse Nodes in k-Group
- Leetcode#25||Reverse Nodes in k-Group
- LeetCode 25 Reverse Nodes in k-Group
- leetcode-25 Reverse Nodes in k-Group
- LeetCode 25: Reverse Nodes in k-Group
- Leetcode #25 Reverse Nodes in k-Group
- LeetCode 25:Reverse Nodes in k-Group
- LeetCode 25 - Reverse Nodes in k-Group
- 快速删除电脑上的大文件
- 南阳acm士兵杀敌系列
- 问题:C-Kermit>c Sorry, you must SET LINE or SET HOST first
- HDU6046 hash 【2017多校联训第二场B】
- Linux修改主机名永久生效
- LeetCode(25)--Reverse Nodes in k-Group
- Linux和Windonws下静态库与动态库(静态库篇)
- 求两个单链表list1与list2的差集,并将结果保存至list1中
- 服务器centos 7.2 LAMP环境安装
- js中常用方法总结
- Android—(提交数据至服务器)
- Spring Cloud Eureka详解
- Configuration--properties(三-1)
- Linux编译安装PHP5.6.31