Runtime Error with code that runs on Ideode


  • 0
    Y

    Hello, my solution seems to run correctly on Ideone, but fails here. Here's the link for solution in Ideone: http://ideone.com/SeszFZ. Wonder if the casting of MinStackElementInMin to MinStackElement could be the culprit but I believe it should be guaranteed that the first field of a struct should be castable by the pointer to the struct. Any ideas on what could be going wrong?

    typedef struct MinStackElement {
        int val;
        MinStackElement* next;
        
        MinStackElement():
        val(0),
        next(NULL){}
        
        MinStackElement(int val_) :
        val(val_),
        next(NULL){}
        
    } MinStackElement;
    
    typedef struct MinStackElementInMin {
        MinStackElement elem;
        MinStackElementInMin* nextInMin;
        
        MinStackElementInMin(int val_) {
            elem.val = val_;
            elem.next = NULL;
            nextInMin = NULL;
        }
    } MinStackElementInMin;
    
    
    class MinStack {
    
    
    MinStackElement* stackHead;
    MinStackElementInMin* stackMin;
    public:
        void push(int x) {
            
            if (stackHead == NULL)
            {
                MinStackElementInMin* newElem = new MinStackElementInMin(x);
                stackHead = (MinStackElement*) (newElem);
                stackMin = newElem;
            }
            else
            {
                if (x <= stackMin->elem.val)
                {
                    MinStackElementInMin* newElem = new MinStackElementInMin(x);
                    newElem->nextInMin = stackMin;
                    stackMin = newElem;
                    stackHead = (MinStackElement*) (newElem);
                }
                else
                {
                    MinStackElement* newElem = new MinStackElement(x);
                    newElem->next = stackHead;
                    stackHead = newElem;
                }
            }
        }
    
        void pop() {
            if (stackHead != NULL)
            {
                MinStackElement* deleted = stackHead;
                if (deleted->val == stackMin->elem.val)
                {
                    stackMin = stackMin->nextInMin;
                    stackHead = stackHead->next;
                    delete ((MinStackElementInMin*) (deleted));
                }
                else
                {
                    stackHead = stackHead->next;
                    delete deleted;
                }
            }
        }
    
        int top() {
            return stackHead->val;
        }
    
        int getMin() {
            return stackMin->elem.val;
        }
        
        MinStack() :
        stackHead(NULL),
        stackMin(NULL) {}
    };
    
    // http://ideone.com/SeszFZ

Log in to reply
 

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