链表中的节点每k个一组反转

链接:www.nowcoder.com/practice/b4…

思路:使用stack来进行反转是十分容易的,然后这一次错了一次,因为我忘了把head移动到下一个节点。还是要细心,避免以后再错了

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        if(head == nullptr || k<=1) {
            return head;
        }

        stack<ListNode*> a;
        ListNode *pHead = new ListNode(0), *now = pHead;
        while(head != nullptr) {
            a.push(head);
            head = head->next;
            if(a.size() >= k) {
                while(!a.empty()) {
                    now->next = a.top();
                    now = a.top();
                    a.pop();
                }
            }
        }


        //剩下的不反转
        ListNode *nex = nullptr,*pre;
        while(!a.empty()) {
            pre = a.top();
            a.pop();
            pre->next = nex;
            nex = pre;
        }
        now->next = nex;

        return pHead->next;
    }
};
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享