码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Nodes in k-Group

时间:2015-09-01 16:33:19      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

又是一道链表的题,关于链表的题好像都是关于指针的,题目都不难吧,主要是需要细心,因为不难,所以代码没有自己写,这里还可以考虑之前做过的链表翻转m至n那道题,然后调用函数就解决了······················

/**
 * 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;
    }
};

  

Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/qiaozhoulin/p/4775903.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!