A very diffrent way, C solution with single-linked-list


  • 0
    S

    At first,I think it can be the direrect way to do it. may be it's a little complecated,but easy to understand.

    typedef struct minstack{
        int val;
    	struct minstack *prev;
    	struct minstack *next;
    	struct minstack *head;
    } MinStack;
    
    /** initialize your data structure here. */
    MinStack* minStackCreate(int maxSize) {
        if (maxSize < 0) return NULL;
    	else
    	{
    		MinStack *ptr = malloc(sizeof(MinStack));
    		ptr->val = 0;
    		ptr->next = NULL;
    		ptr->prev = NULL;
    		ptr->head = ptr;
    		return ptr;
    	}
    	return NULL;
    }
    
    void minStackPush(MinStack* obj, int x) {
        if (obj->next == NULL)
    	{
    		MinStack *ptr = malloc(sizeof(MinStack));
    		ptr->val = x;
    		ptr->next = NULL;
    		ptr->prev = obj;
    		ptr->head = obj;
    		obj->next = ptr;
    	}
    	else
    	{
    		MinStack *ptr = malloc(sizeof(MinStack));
    		ptr->val = x;
    		ptr->next = obj->next;
    		if (ptr->next != NULL)
    		{
    			ptr->next->prev = ptr;
    		}
    		obj->next = ptr;
    		ptr->prev = obj;
    		ptr->head = obj;
    	}
    }
    
    void minStackPop(MinStack* obj) {
        if (obj != NULL)
    	{
    		MinStack *ptr = obj->next;
    		if (obj->next != NULL)
    		{
    			obj->next = ptr->next;
    			if (obj->next != NULL)
    			{
    				obj->next->prev = obj;
    			}
    			free(ptr);
    		}
    	}
    }
    
    int minStackTop(MinStack* obj) {
      	if (obj != NULL)
    	{
    		if (obj->next != NULL)
    		{
    			return obj->next->val;
    		}
    	}
    	return 0;  
    }
    
    int minStackGetMin(MinStack* obj) {
        if (obj == NULL)
    	{
    		return 0;
    	}
    	MinStack *p = obj->next;
    	int min = 0;
    	if (p != NULL)
    	{
    		min = p->val;
    	}
    
    	while (p != NULL){
    		if (p->val < min) {
    			min = p->val;
    		}
    		p = p->next;
    	}
    	return min;
    }
    
    void minStackFree(MinStack* obj) {
        if (obj != NULL)
    	{
    		MinStack* ptr = obj->next;
    		free(obj);
    		while (ptr != NULL)
    		{
    			MinStack* ptr1 = ptr->next;
    			free(ptr);
    			ptr = ptr1;
    		}
    	}
    }
    

  • 0
    S

    I think It's better to take off the pointer head~


Log in to reply
 

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