C++ 24ms,used stack.


  • -1
    F

    used a stack<ListNode*>,determine the number of nodes in the stack。

    ListNode* reverseKGroup(ListNode* head, int k) {
        stack<ListNode*>atime;
        ListNode* node=NULL;
        ListNode* lastNode=NULL;
        ListNode* ans=NULL;
        int flag=0,turn=0;
        while(head!=NULL)
        {
            while(head!=NULL&&turn<k)
            {
                atime.push(head);
                head=head->next;
                turn++;
            }
            if(turn==k)
            {
                for(int i=0;i<k;i++)
                {
                    node=atime.top();
                    if(!flag)
                    {
                        flag=1;
                        ans=node;
                    }
                    if(lastNode!=NULL)
                    {
                        lastNode->next=node;
                    }
                    lastNode=node;
                    atime.pop();
                }
                lastNode->next=NULL;
                turn=0;
            }
            else
            {
                for(int i=0;i<turn;i++)
                {
                    node=atime.top();
                    atime.pop();
                }
                if(!flag)
                {
                    ans=node;
                }
                if(lastNode!=NULL)
                {
                    lastNode->next=node;
                }
            }
        }
        return ans;
    }

  • 0
    J

    Requires linear (extra) space for the stack.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.