share my C solution with only one stack(accepted)


  • 0
    H
    /** initialize your data structure here. */
    MinStack* minStackCreate(int maxSize)//correct
    {
      MinStack* myStack;
      myStack = (MinStack*)malloc(sizeof(MinStack));
      myStack->head = (int*)malloc(sizeof(int) * maxSize);
      if(!myStack->head)
        {
          perror("malloc");
          exit(-1);
        }
      myStack->stackPointer = -1;
      return myStack;
    }
    void minStackPush(MinStack* obj, int x)//correct
    {
      //这里应判断栈没有越界
      obj->head[++(obj->stackPointer)] = x;
      if((obj->stackPointer == 0)||(x < obj->minum))//如果栈里只有一个值,那么最小值就为他自己;否则将当前值与最小值比较
        {
          obj->minum = x;
        }
    }
    
    void minStackPop(MinStack* obj)//correct
    {
      int i;
      if(obj->stackPointer > -1)
        {
          (obj->stackPointer)--;
          obj->minum = obj->head[obj->stackPointer];
          for(i = obj->stackPointer; i >= 0; --i)
            {
              if(obj->head[i] < obj->minum)
               obj-> minum = obj->head[i];
            }
        }
    }
    
    int minStackTop(MinStack* obj)
    {
      if(obj->stackPointer >= 0)
        {
          return obj->head[obj->stackPointer];
        }
      exit(-1);
    }
    
    int minStackGetMin(MinStack* obj)//correct
    {
      return obj->minum;
    }
    
    void minStackFree(MinStack* obj)//correct
    {
      free(obj);
    }
    

Log in to reply
 

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