aboutsummaryrefslogtreecommitdiff
path: root/design_stack_increment_op.c
blob: fbab1f44f745ee0a6f355a0dcc1dd5d865cd2205 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// 1381. Design a Stack With Increment Operation
#include "leetcode.h"

/*
 * design a stack that supports increment operations on its elements. implement
 * the function increment that increments the bottom 'k' elements of the stack
 * by 'val' if there are less than 'k' elements in the stack, increment all the
 * elements in the stack
 */

typedef struct {
  int *data;
  int idx;
  int size;
} CustomStack;

CustomStack *customStackCreate(int maxSize) {
  CustomStack *obj = malloc(sizeof(CustomStack));
  obj->data = (int *)calloc(maxSize, sizeof(int));
  obj->size = maxSize;
  obj->idx = 0;
  return obj;
}

void customStackPush(CustomStack *obj, int x) {
  if (obj->idx == obj->size)
    return;
  obj->data[obj->idx] = x;
  obj->idx++;
}

int customStackPop(CustomStack *obj) {
  if (!(obj->idx))
    return -1;
  obj->idx--;
  return obj->data[obj->idx];
}

void customStackIncrement(CustomStack *obj, int k, int val) {
  int min = k < obj->idx ? k : obj->idx;
  for (int i = 0; i < min; i++)
    obj->data[i] += val;
}

void customStackFree(CustomStack *obj) {
  free(obj->data);
  free(obj);
}

int main() {
  CustomStack *obj = customStackCreate(3);
  customStackPush(obj, 1);
  customStackPush(obj, 2);
  printf("%d\n", customStackPop(obj)); // expect: 2
  customStackPush(obj, 2);
  customStackPush(obj, 3);
  customStackPush(obj, 4);
  customStackIncrement(obj, 5, 100);
  printf("%d\n", customStackPop(obj)); // expect: 103
  printf("%d\n", customStackPop(obj)); // expect: 202
  printf("%d\n", customStackPop(obj)); // expect: 201
  printf("%d\n", customStackPop(obj)); // expect: -1
  customStackFree(obj);
}