您的位置:首页 > Web前端 > Node.js

2017-09-11 LeetCode_025 Reverse Nodes in k-Group

2017-09-11 13:17 513 查看
25. 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.
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.
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


solution:

class Solution {


2

public:


3

   ListNode* reverseKGroup(ListNode* head, int k) {


4

       int d = 0;


5

       ListNode *p = head;


6

       while (p != NULL) {


7

           d++; p = p->next;


8

}


9

if (d < k) return head;


10

if (k <= 1) return head;


11

p = head;


12

ListNode *q = head->next, *r = head->next->next;


13

int k_ = k-2;


14

while (k_--) {


15

q->next = p;


16

p = q; q = r; r = r->next;


17

}


18

q->next = p;


19

head->next = reverseKGroup(r, k);


20

return q;


21

   }


22

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode