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

[leetcode]Reverse Nodes in k-Group

2014-01-04 22:25 260 查看
又是链表题,最近都不想做了。。。不过今天状态不好,做做吧

把链表分成大小为k的各种块,然后反转这些块。

想想还是有点麻烦的感觉。。。。

要考虑前面,后面的。。。。

那就递归吧。。。这应该就简单了。。。

就处理当前k个就好了。。。

找到这k个。。。reverse。。。

next指向后面处理好的head(递归

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head){
ListNode* prev = nullptr;
ListNode* nowNode = head;
while(nowNode){
ListNode* next = nowNode -> next;
nowNode -> next =  prev;
prev = nowNode;
nowNode = next;
}
return prev;
}
ListNode *reverseKGroup(ListNode *head, int k) {
if(head == nullptr || head -> next == nullptr || k < 2) return head;

int cnt = 1;
ListNode* nowHead = head;
ListNode* nowNode = head;
while(nowNode && cnt < k){
cnt ++;
nowNode = nowNode -> next;
}
if(nowNode && cnt == k){
ListNode* tail = reverseKGroup(nowNode -> next , k);
nowNode -> next = nullptr;
head = reverse(head);
nowHead -> next = tail;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: