Leetcode:reverse Nodes in K-group

Source: Internet
Author: User

Reverse Nodes in K-groupTotal Accepted: 57696 Total Submissions: 210241 Difficulty: Hard

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

Subscribe to see which companies asked this question

Hide TagsLinked ListHide Similar Problems(E) Swap Nodes in Pairs


























Ideas:

/*k=3 first reversal, initial status: -1, 1, 2, 3, 4--5 |    |    | Pre  cur  tmp after 1th operation: -1, 2, 1, 3, 4 and 5 | |    | PRE       cur  tmp after 2nd operation: -1, 3-& Gt 2, 1, 4, 5 |              |    | Pre            cur  tmp second reversal, initial status: -1, 3, 2, 1, 4--5                |    |    |                Pre  cur  tmp...*/


Code

/** * 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 | | k<=1) return                Head        ListNode dummy (0);        Dummy.next = head;        ListNode *pre = &dummy;        ListNode *cur = head;                ListNode *tmp;        int len = 0;            while (cur) {len++;        Cur = cur->next;            } while (len>=k) {cur = pre->next;            TMP = cur->next;                for (int i=1;i<k;i++) {Cur->next = tmp->next;                Tmp->next = pre->next;                Pre->next = tmp;            TMP = cur->next;            } pre = cur;        Len-= k;    } return dummy.next; }};


Leetcode:reverse Nodes in K-group

Related Article

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.