Leetcode 25. k个一组翻转链表

指针的next反转一下,再把链表接起来
如1->2->3->4->5反转2->3->4的时候
先1 2<-3<-4 5 再1->4和2->5

/**
* 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) {
        ListNode *l = head, *r = head, *tr, *tl, *T, *pl = NULL, *nr;
        if (!head) return head;
        for (int i = 1; i < k; ++i) {
            if (r->next) r = r->next;
            else return head;
        }
        head = r;
        do {
            nr = r->next, tr = l->next, tl = l;
            while (tl != r) {
                T = tr->next;
                tr->next = tl;
                tl = tr, tr = T;
            }
            if (pl) pl->next = r;
            l->next = nr;
            if (!nr) return head;
            pl = l;
            r = l = nr;
            for (int i = 1; i < k; ++i) {
                if (r->next) r = r->next;
                else return head;
            }
        } while (1);
    }
};

你可能感兴趣的:(LeetCode)