LeetCode: Reverse Nodes in k-Group
来源:互联网 发布:域名服务器设置 编辑:程序博客网 时间:2024/06/05 10:43
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
思路:用一个指针记录已经转置的链表的尾节点。
从头节点开始,设置一个指针对其移动k个,将其断开,调用原地转置链表的代码。转置链表插入到已经转置好的链表的尾部。如果最后剩下不足k个,直接将剩余链表插入到尾部
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: //原地转置链表函数 ListNode* reverseList(ListNode* head) { if(head == nullptr) return head; ListNode *p = head; ListNode *q = head->next; head->next = nullptr; while(q != nullptr) { ListNode *t = q->next; q->next = p; p = q; q = t; } return p; } ListNode* reverseKGroup(ListNode* head, int k) { //头节点为空或者分组为1可以直接返回 if(head == nullptr || k==1) return head; //用于记录头节点和尾节点 ListNode* nhead = nullptr; ListNode* ntail = nullptr; //需要转置链表的头 p和尾 q ListNode* p = head; ListNode* q = p; while(q!=nullptr) { //找到长度为k的链表 for(int step = 0; q != nullptr && step < (k-1); ++ step) q = q->next; if(q == nullptr) { //如果没找到直接插入到尾部 if(nhead == nullptr) nhead =head; else ntail->next = p; break; } else { //找到了记录下一节点,并分割出一个链表进行转置 ListNode* t = q->next; q->next = nullptr; reverseList(p); //将转置链表插入尾部,之前的头p成了尾,之前的尾q成为头。设置新的尾部为p if(nhead == nullptr) { ntail = p; nhead = q; } else { ntail->next = q; ntail = p; } q = t; p = t; } } return nhead; }};
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
- NB programmers
- tomcat改命令窗口标题的方法
- struts1和struts2的几点区别
- 多线程同步(Lock)
- 一个健壮的MD5算法
- LeetCode: Reverse Nodes in k-Group
- spark中stream编程指导(二)
- Cocos2d-x制作跳棋第四步:胜负判断、AI具体实现及实现特殊组合动作的小技巧
- HDU 2031
- 黑马程序员——Java基础---正则表达式
- 二叉树的遍历本质 - 前序,中序,后序
- PowerDesigner使用时经常报打印错误,提示安装打印机
- KMP字符串匹配算法——用最容易理解的方式描述
- Android TV 视图体系分析