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

LeetCode : Reverse Nodes in k-Group

2012-12-06 16:20 281 查看
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


刚开始没理解题意。其实就是k个k个做。和之前那个差不多。

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL){return NULL;}
int count = 0;
ListNode * p1 = head;
while(p1){
count++;
p1 = p1->next;
}
if(count < k){return head;}
p1 = head;
ListNode * last = p1;
ListNode * p2 = p1->next;
ListNode * p3;
if(p2 == NULL){
return head;
}
int i = 1;
for(i = 1 ; i< k && p1 && p2; ++i){
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next = p2;
if(count - k >= k){
last->next = reverseKGroup(last->next, k);
}
return p1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: