Leetcode Reverse Nodes in K-group

Source: Internet
Author: User

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, and only nodes itself is 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

Ideas:

One: This topic can refer to swap nodes in pairs and reverse link list. Use three pointers (pre, Start,then) method to solve, count how many group, the last group does not make any changes.

Two: Recursive method can be used.

Is every k under, recursion once, then k after that next normal walk, K inside call recursive. Notice that the starting initial condition within the recursion is judged so that it returns well.

1 classSolution {2  Public:3ListNode *reversekgroup (ListNode *head,intk)4     {5         6         if(head = = NULL | | head->next = NULL | | k<2)7             returnhead;8         9ListNode * Fakenode =NewListNode (0);TenFakenode-Next =head; OneListNode * p =head; A         intLength =0; -          while(P) -         { thelength++; -p = p->Next; -         } -         if(k>length) +             returnFakenode->Next; -ListNode * pre =Fakenode; +ListNode * start = pre->Next; AListNode * then = startNext; at  -         intTotal =0; -         intCNT =0; -          while(then!=NULL) -         { -              while(cnt!=k-1&&Then ) in             { -CNT + +; toStart->next = then->Next; +Then->next = pre->Next; -Pre->next =then ; thethen = start->Next; *             } $Total + +;Panax Notoginseng             if(Total = = length/k) -                  Break; thePre =start; +Start = pre->Next; Athen = start->Next; theCNT =0; +         } -         returnFakenode->Next; $     } $};

Leetcode Reverse Nodes in K-group

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.