C++ The results of OJ is different with VS (not use stl)


  • 0
    Q

    OJ : -1,-1,0

    VS : -2, -1, -2

    VS‘s result is correct, OJ's result is wrong.

    #include <iostream>
    using namespace std;
    struct Node {
    	int val;
    	Node* next;
    };
    class MinStack {
    private:
    	Node* head;
    	Node* min;
    public:
    	MinStack() {
    		head = new Node;
    		head->next = NULL;
    		min = new Node;
    		min->next = NULL;
    	}
    	~MinStack() {
    		delete head;
    		head = NULL;
    		delete min;
    		min = NULL;
    	}
    public:
    	void push(int x) {
    		Node* elem = new Node;
    		elem->val = x;
    		elem->next = head->next;
    		head->next = elem;
    		if (min->next == NULL || x <= min->val) {
    			Node* min_elem = new Node;
    			min_elem->val = x;
    			min_elem->next = min->next;
    			min->next = min_elem;
    		}
    	}
    
    	void pop() {
    		if (head->next == NULL)
    			return;
    		Node* top_elem = head->next;
    		head->next = head->next->next;
    		if (min->next != NULL && top_elem->val == min->next->val) {
    			Node* min_elem = min->next;
    			min->next = min->next->next;
    			delete min_elem;
    			min_elem = NULL;
    		}
    		delete top_elem;
    		top_elem = NULL;
    	}
    
    	int top() {
    		if (head->next == NULL)
    			return int();
    		return head->next->val;
    	}
    
    	int getMin() {
    		if (min->next == NULL)
    			return int();
    		return min->next->val;
    	}
    };
    
    int main() {
    	MinStack sol;
    	sol.push(-2);
    	sol.push(0);
    	sol.push(-1);
    	cout << sol.getMin() << endl;
    	cout << sol.top() << endl;;
    	sol.pop();
    	cout << sol.getMin() << endl;
    	sol.pop();
    	return 0;
    }

Log in to reply
 

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