43-Reverse Nodes in k-Group
来源:互联网 发布:企业网络拓扑结构图 编辑:程序博客网 时间:2024/05/22 09:48
- Reverse Nodes in k-Group My Submissions QuestionEditorial Solution
Total Accepted: 58690 Total Submissions: 212820 Difficulty: Hard
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
当之无愧的难题,其实思路比较简明,但是要写出完全无bug的代码简直太难了,改了很多遍才改到无bug,因为里面的指针运算太多了,一不注意就掉坑了,改变了指针所向内容的next,确仍然引用
结果:
Submission Details
81 / 81 test cases passed.
Status: Accepted
Runtime: 24 ms
beats:41.82%
思路:找到每一段末尾标记,然后该段范围内进行逆转,同时保留逆转后的末尾元素。
class Solution {public: ListNode* reverseKGroup(ListNode* head, int k) { if(head==NULL||head->next==NULL||k==1)return head; ListNode *fir=head,*sec=head,*pre_fir=NULL,*pre_sec=NULL; int finished=0; int count=1; while(!finished){ int i=1; while(i++<k&&sec!=NULL){sec=sec->next;} //fir.....sec段总的K个元素 ListNode *sec_next=(sec==NULL)?NULL:sec->next; if((i-1)==k&&(sec!=NULL)){ //注意,只有当找了k次且最后一次找到了(不为空)才进行这段元素原地逆转 ListNode *tmp = fir->next; //逆转时的当前元素 ListNode *prenode = fir; //逆转时保留的前一元素 while(tmp!=sec_next) //当前元素没到sec末尾元素, { ListNode *nextnode = (tmp->next); //保存当前元素的下一元素 tmp->next = prenode; //当前元素指向前一个元素 prenode = tmp; //前一元素右移 tmp = nextnode; //当前元素右移 } fir->next = NULL; //第一段的首元素变成末尾元素。 if(pre_fir!=NULL){pre_fir->next = prenode;pre_fir = fir;}//pre_fir上一段逆转后的末尾指向当前的逆转后的开头 else {head = prenode;pre_fir=fir;}//针对第一次前一段的逆转前的为空 fir = sec_next; //开始下一段元素逆转,sec_next保存上一段sec的下一元素 sec = fir; //将sec置为fir一样的值,开始逆转流程。 } else { finished = 1; if(pre_fir!=NULL)pre_fir->next = fir; } } return head; }};
0 0
- 43-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
- java中如何给实现的接口传递变量以内部类为例
- 专题三 第六题
- sp3接着延续上一片 讲update
- 图论最短路径算法-Dijkstra算法-单源最短路径-JAVA语言描述
- 全面理解虚拟DOM,实现虚拟DOM
- 43-Reverse Nodes in k-Group
- sp3 接着上一片 delete
- Poj 2891 Strange Way to Express Integers【crt】
- Problem Q
- Coremail手机版页面持久型XSS实践
- 【AKOJ】1114-水仙花数
- [Unity3D]简单使用Protobuf-net(三)
- 深度剖析:如何实现一个 Virtual DOM 算法
- JS原型链