Reverse Nodes in k-Group
来源:互联网 发布:linux系统怎么样 编辑:程序博客网 时间:2024/05/16 17:01
描述
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的节点反转,不够k值长度的片断不反转。
分析:
根据循环,每遍历k个元素,进行一次翻转。
class Solution {public: ListNode *reverseKGroup(ListNode *head, int k) { if (head == nullptr || head->next == nullptr || k < 2) return head; ListNode dummy(-1); dummy.next = head; for(ListNode *prev = &dummy, *end = head; end; end = prev->next) { for (int i = 1; i < k && end; i++) end = end->next; if (end == nullptr) break; // 不足k 个 prev = reverse(prev, prev->next, end);//reverse翻转函数,将prev到end的链表翻转 //返回翻转后的倒数第一个元素 } return dummy.next; }// prev 是first 前一个元素, [begin, end] 闭区间,保证三者都不为null// 返回反转后的倒数第1 个元素 ListNode* reverse(ListNode *prev, ListNode *begin, ListNode *end) { ListNode *end_next = end->next; ListNode *p = begin; ListNode *cur = p->next; ListNode *next = cur->next; while(cur != end_next){ cur->next = p; p = cur; cur = next; next = next ? next->next : nullptr; } begin->next = end_next; prev->next = end; return begin;}};
0 0
- Reverse Nodes in k-Group
- Reverse Nodes in K-Group
- Reverse Nodes in k-Group
- Reverse Nodes In K Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- javascript数组循环遍历之foreach
- JAVA BASE64 加密解密实现代码
- mysql 数据库参数配置
- Sublime text 2/3 中 Package Control 的安装与使用方法
- 查找一个节点是不是另外一个节点的后代
- Reverse Nodes in k-Group
- hdoj 1509 Windows Message Queue 【STL 优先队列】
- SAP CRM有哪些版本
- JNI Hook java层方法
- Web Service学习-CXF开发Web Service实例demo(一)
- UICollectionView中cell的border问题
- Code Blocks 集成 wxWidgets
- Android ADB server didn't ACK * failed to start daemon * 简单有效的解决方案
- hdu1978 How many ways 解题报告