leetcode : Reverse Nodes in k-Group
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
似乎难的地方在于边界问题~,但是,直接先遍历一遍链表数一下有几个元素不就可以了么
又不影响时间复杂度,反正都是n。
AC代码:
ListNode *reverseKGroup(ListNode *head, int k) { int len = 0; auto h = head; while(h){ h = h->next; ++len; } h = head; ListNode *ret = nullptr, *tail = nullptr, *p; for(int i = 0; i < len / k; ++i){ ListNode *currentHead = nullptr; ListNode *currentTail = h; for(int j = 0; j < k; ++j){ p = h; h = h->next; p->next = currentHead; currentHead = p; } if(!ret){ ret = currentHead; tail = currentTail; }else{ tail->next = currentHead; tail = currentTail; } } if(ret) tail->next = h; else return h; return ret; }
浙公网安备 33010602011771号