LeetCode 25.Reverse Nodes in k-Group

简单链表翻转,还是wa了一发。。

递归就可以了,翻转时需要使用的头和尾要存起来

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rev(ListNode* p,int k)
    {
        ListNode* shit=NULL;
        ListNode* pre=NULL;
        ListNode* fuck=p;
        int idx=0;
        while(p!=NULL)
        {
            shit=p->next;
            p->next=pre;
            pre=p;
            p=shit;
            idx++;
            if(idx==k)
            {
                fuck->next=rev(p,k);
                return pre;
            }
        }
        if(idx<k)
        {
            while(pre!=NULL)
            {
                shit=pre->next;
                pre->next=p;
                p=pre;
                pre=shit;
            }
            return p;
        }
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        return rev(head,k);
    }
};
原文地址:https://www.cnblogs.com/bitch1319453/p/6604656.html