LeetCode-25- Reverse Nodes in k-Group

痛定思痛。 2021-12-15 14:01 244阅读 0赞

算法描述:

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed.

解题思路:细节实现题。

  1. ListNode* reverseKGroup(ListNode* head, int k) {
  2. if(head == nullptr) return head;
  3. int count =0;
  4. ListNode* cur = head;
  5. while(cur!=nullptr && count < k){
  6. cur=cur->next;
  7. count++;
  8. }
  9. if(count==k){
  10. cur = reverseKGroup(cur,k);
  11. while(count--){
  12. ListNode* temp = head->next;
  13. head->next=cur;
  14. cur=head;
  15. head=temp;
  16. }
  17. head=cur;
  18. }
  19. return head;
  20. }

转载于:https://www.cnblogs.com/nobodywang/p/10362104.html

发表评论

表情:
评论列表 (有 0 条评论,244人围观)

还没有评论,来说两句吧...

相关阅读