C++ Solution for Reverse Nodes in k-Group (LeetCode 25)
- ListNode *b=new ListNode(1);
- ListNode *c=new ListNode(2);
- ListNode *d=new ListNode(3);
- ListNode *e=new ListNode(4);
- ListNode *f=new ListNode(5);
- ListNode *g=new ListNode(6);
- a->next=b;
- b->next=c;
- c->next=d;
- d->next=e;
- e->next=f;
- f->next=g;
- g->next=NULL;
- Solution sol;
- ListNode *head=sol.reverseKGroup(a,4);
- while(head!=NULL){
-
cout<<head->val<<' '; -
head=head->next; - }
- cout<<endl;
- return 0; +} §§ --- 25. Reverse Nodes in k-Group/Readme.md §§ 1000
25. Reverse Nodes in k-Group
Difficulty for me
Medium
Complexity
time complexity = O(n)
space complexity = O(1)
runtime: beat 71.25%
Summary
reverse
每k个node反转,和206题类似,但是有个难点是找到每次反转的末尾node,其实可以用一个指针,每次指向末尾node.
Tips
- 链表最后一段不够k个,不需要反转
- 记得最后把尾节点的next置为空
原文地址: https://www.cveoy.top/t/topic/lhYd 著作权归作者所有。请勿转载和采集!