We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Stacks
  4. Maximum Element
  5. Discussions

Maximum Element

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • dakshilgorasiya1
    4 months ago+ 0 comments
    #include <stdio.h>
    #include <stdlib.h>
    
    struct stack
    {
        int *arr;
        int size;
        int top;
    };
    
    int isEmpty(struct stack *s)
    {
        if(s->top == -1)
            return 1;
        return 0;
    }
    
    int isFull(struct stack *s)
    {
        if(s->top == s->size - 1)
            return 1;
        return 0;
    }
    
    void push(struct stack *s, int data)
    {
        if(!isFull(s))
        {
            s->top++;
            s->arr[s->top] = data;
        }
        else {
            printf("Stack overflow\n");
        }
    }
    
    int pop(struct stack *s)
    {
        int ans = -1;
        if(isEmpty(s))
            printf("Stack underflow\n");
        else {
            ans = s->arr[s->top];
            s->top--;
        }
        return ans;
    }
    
    int maximum(struct stack *s)
    {
        int max = s->arr[0];
        for(int i = 0; i <= s->top; i++)
        {
            if(max < s->arr[i])
                max = s->arr[i];
        }
        return max;
    }
    
    int main()
    {
        int query;
        scanf("%d",&query);
        struct stack *s = (struct stack *)malloc(sizeof(struct stack));
        s->size = query + 1;
        s->top = -1;
        s->arr = (int *)malloc(s->size * sizeof(int));
        for(int i = 0; i < query; i++)
        {
            int type;
            scanf("%d",&type);
            if(type == 1)
            {
                int data;
                scanf("%d",&data);
                push(s,data);
            }
            else if(type == 2)
            {
                pop(s);
            }
            else
            {
                int max = maximum(s);
                printf("%d\n",max);
            }
        }
    }
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy