Leetcode25题k个一组翻转链表C++解答

这题懵逼的做出来了,懵在最后如何返回链表首节点,凭着感觉写了个dummy,结果就AC了,过了之后想半天没想明白怎么就AC了?在VS上调试发现是pre的功劳。首次进if时pre仍代表dummy,把dummy更新了。真是无心插柳。

/**
 * 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) {
        stack<ListNode*> s;
        int cnt = 0;
        ListNode *dummy = new ListNode(0);
        dummy->next = head;
        ListNode *pre = dummy;
        while(head)
        {
            cnt++;
            if(cnt == k)
            {
                cnt = 0;
                ListNode *tail = head -> next;
                pre->next = head;//**关键**
                while(!s.empty())
                {
                    ListNode *next = s.top();
                    head->next = next;
                    head = head ->next;
                    s.pop();
                }
                head ->next = tail;
                pre = head;
            }
            else
            {
                s.push(head);
            }    
            head = head->next;
        }
        return dummy->next;
    }
};
发布了26 篇原创文章 · 获赞 6 · 访问量 6470

猜你喜欢

转载自blog.csdn.net/weixin_43975128/article/details/90203010