1. /**
    2. * @param {number} maxSize
    3. */
    4. var CustomStack = function(maxSize) {
    5. this.stack = [];
    6. this.maxSize = maxSize;
    7. };
    8. /**
    9. * @param {number} x
    10. * @return {void}
    11. */
    12. CustomStack.prototype.push = function(x) {
    13. if (this.stack.length < this.maxSize) {
    14. this.stack[this.stack.length] = x;
    15. }
    16. };
    17. /**
    18. * @return {number}
    19. */
    20. CustomStack.prototype.pop = function() {
    21. if (this.stack.length) {
    22. const top = this.stack[this.stack.length-1];
    23. this.stack.length--
    24. return top;
    25. }
    26. this.stack.length = 0;
    27. this.top = 0;
    28. return -1
    29. };
    30. /**
    31. * @param {number} k
    32. * @param {number} val
    33. * @return {void}
    34. */
    35. CustomStack.prototype.increment = function(k, val) {
    36. k = Math.min(this.stack.length, k);
    37. for (let i = 0; i < k; i++) {
    38. this.stack[i] += val
    39. }
    40. };
    41. var customStack = new CustomStack(3)
    42. customStack.push(1);
    43. customStack.push(2);
    44. customStack.pop();
    45. customStack.push(2);
    46. customStack.push(3);
    47. customStack.push(4);
    48. customStack.increment(5, 100); // 栈变为 [101, 102, 103]
    49. //customStack.increment(2, 100); // 栈变为 [201, 202, 103]
    50. // customStack.pop(); // 返回 103 --> 返回栈顶值 103,栈变为 [201, 202]
    51. // customStack.pop(); // 返回 202 --> 返回栈顶值 202,栈变为 [201]
    52. // customStack.pop(); // 返回 201 --> 返回栈顶值 201,栈变为 []
    53. // customStack.pop();
    54. console.log(customStack);
    55. /**
    56. * Your CustomStack object will be instantiated and called as such:
    57. * var obj = new CustomStack(maxSize)
    58. * obj.push(x)
    59. * var param_2 = obj.pop()
    60. * obj.increment(k,val)
    61. */