My accepted C++ solution using stack


  • 0
    C
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            if(n == m || head == nullptr) return head;
            
            ListNode * subHead = head;
            int mm = m - 1;
            while(mm--)
                subHead = subHead->next;
            ListNode *ptr = subHead;
            stack<int> cache;
            int nn = n - m + 1;
            while(nn--)
            {
                cache.push(ptr->val);
                ptr = ptr->next;
            }
            ListNode *subTail = ptr;
            ptr = subHead;
            while(ptr != subTail)
            {
                ptr->val = cache.top();
                cache.pop();
                ptr = ptr->next;
            }
            return head;
        }
    };
    

  • 0
    R

    So I am curious, can you explain why you did the lines;
    int mm = m - 1;
    int nn = n -m + 1;

    I came up with a similar solution except i used
    for (int i = 1 i < m i++)
    for(int i = m i < n i++)

    Using these failed to get the right answer. Can I pick your brain on this?


  • 1
    C

    Just a little mistake.
    It should be for(int i = m - 1; i < n; i++) when you try to push nodes to stack.


Log in to reply
 

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