25. Reverse Nodes in k-Group
2017-01-31 00:31
309 查看
1刷
上面一提的加强版,思路很简单,每k个就调用一个函数换一次
难点!小细节,这种错!要十分注意每一次换了位置之后的前后的指针标记会变化!!!
2刷
还是链表的各种操作,要3刷,2刷再次学了方法
上面一提的加强版,思路很简单,每k个就调用一个函数换一次
难点!小细节,这种错!要十分注意每一次换了位置之后的前后的指针标记会变化!!!
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void changethelist(ListNode* a, ListNode* b, ListNode* first, ListNode* end){ ListNode *t1, *t2, *t; t1 = a; t2 = a -> next; while(t2 != b){ t = t2 -> next; t2 -> next = t1; t1 = t2; t2 = t; } t2 -> next = t1; if(first != NULL) first -> next = b; a -> next = end; } ListNode* reverseKGroup(ListNode* head, int k) { if(head == NULL || k == 1) return head; ListNode *h, *a, *last, *n; h = head; int num = 0; while(head != NULL){ num++; if(num == k) h = head; if(num % k == 1) a = head; //if(num % k == 1 && num != 1) return head; if(num == k){ n = head -> next; changethelist(a, head, NULL, head -> next); last = a; head = n; } else if(num % k == 0){ n = head -> next; changethelist(a, head, last, head -> next); last = a; head = n; } else{ head = head -> next; continue; } } return h; } };
2刷
还是链表的各种操作,要3刷,2刷再次学了方法
/** * 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==NULL||k==1) return head; int num=0; ListNode *preheader = new ListNode(-1); preheader->next = head; ListNode *cur = preheader, *nex, *pre = preheader; while(cur = cur->next) num++; while(num>=k) { cur = pre->next; nex = cur->next; for(int i=1;i<k;++i) { cur->next=nex->next; nex->next=pre->next; pre->next=nex; nex=cur->next; } pre = cur; num-=k; } return preheader->next; } };
相关文章推荐
- SELECT TOP n or SELECT TOP Random n Rows From a Table For Each Category or Group
- GCD之Group
- android中radioGroup动态添加radioButton
- MYSQL:GROUP_CONCAT,SUBSTRING_INDEX的妙用(转)
- RadioButton和RadioGroup一点使用心得
- 自定义ViewGroup,并添加高仿雪球app分享弹出动画。
- extjs 3.0 radioGroup的问题解决办法
- group_concat函数详解
- [LeetCode 49]Group Anagrams(利用数据结构和排序简化问题)
- oracle group by
- MongoDB聚合操作 (group, aggregate, mapReduce操作)
- AtCoder Grand Contest 012 A - AtCoder Group Contest(贪心)
- h:panelGrid、h:panelGroup标签学习
- group_concat函数详解
- 史上最简单侧滑菜单,0耦合,支持任意ViewGroup。一步集成侧滑(删除)菜单,高仿QQ、IOS。~
- 正则基础之——捕获组(capture group)
- corona group move
- 算法分析与设计课程(7):【leetcode】Reverse Nodes in k-Group
- oracle GROUP 函數(AVG,COUNT,MAX,MIN,SUM,NVL,UID,USER,USERENV,DECODE)
- FlowRadioGroup给RadioGroup的子控件随意排版