Leetcode217: Reverse Nodes in k-Group
来源:互联网 发布:用电脑看小说的软件 编辑:程序博客网 时间:2024/05/22 12:21
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
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* reverseKGroup(ListNode* head ,int k) { if (!head||!head->next||k<=1) return head; ListNode* pFirst=head; ListNode* pBefore=NULL; ListNode* pKth=pFirst; while(1) { int cnt=k-1; while(cnt&&pKth) { pKth=pKth->next; cnt--; } if ( cnt>0 || pKth==NULL) break; reverse(pBefore,pFirst,pKth); if (pBefore==NULL) head=pFirst; pBefore=pKth; pFirst=pKth->next; pKth=pFirst; } return head; } void reverse(ListNode* pBefore,ListNode*& pFirst,ListNode*& pKth) { ListNode* pN=pFirst; while(pN!=pKth) { ListNode* pTmp=pN->next; pN->next=pKth->next; pKth->next=pN; pN=pTmp; } ListNode* pTmp=pFirst; pFirst=pKth; pKth=pTmp; if (pBefore) pBefore->next=pFirst; } };
0 0
- Leetcode217: 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
- 深入 Docker:容器和镜像
- DOM扩展:DOM API的进一步增强[总结篇-上]
- JVM的GC简介和实例
- 【设计模式】适配器模式
- linux网络编程实用命令
- Leetcode217: Reverse Nodes in k-Group
- [黑马IOS自学第十七篇]OC BLOCK学习
- Herd Mentality(群集心态)
- xshell window远程到linux服务器,文件传输
- 数据库编码修改
- 谷歌J2ObjC:打破Android应用与iOS应用之间的语言障碍
- 科摩多数据备份工具下载
- Windows程序内部运行机制学习
- 在c++中尾递归,普通递归,循环的效率对比