首页 > 解决方案 > 基于堆栈操作c ++计算元素的最大值

问题描述

给你一堆 N 个整数。在一个操作中,您既可以从堆栈中弹出一个元素,也可以将任何弹出的元素压入堆栈。您需要在执行完 K 次操作后最大化堆栈的顶部元素。如果堆栈在执行 K 次操作后变空并且没有其他方法使堆栈不为空,则打印 -1。

我正在动态分配内存然后释放内存。我无法理解为什么我会面临这个问题。

#include "pch.h"
#include<iostream>
using namespace std;
int main()
{
int n, x, max;
cin >> n;
cin >> x;
int* arr = new int[n];
    //Storing the values from the last, since the first element represents 
    //top of the stack, so the first element would be latest element which 
    //will be pushed into the stack
for (int i = n; i > 0; i--)
{
    cin >> arr[i];
}
max = arr[n];
    //Finding the max by iterating from the last position to the no of 
    //stack operations performed.
for (int i = n; i >= x; i--)
{
    if (arr[i] > max)
    {
        max = arr[i];
    }
}
cout << max;
delete arr;
return 0;
}

输入 :

6 4
1 2 4 3 3 5

预期输出:

4

错误:

Error Message : Debug Error ! Program :- Heap Corruption detected : after 
normal block c#2368 at 0x01d21e30. CRT detected that the application wrote 
memory after end of heap buffer.

标签: c++arraysc++11data-structuresstack

解决方案


您的代码中有几个错误:三个索引错误和一个内存释放错误。首先,在 C++ 中,数组索引总是从 0 开始。所以 n 元素数组的第一个有效索引是 0,最后一个有效索引是 n-1。

1)由于这些原因,第一个循环应该是这样的:

for (int i = n-1; i >= 0; i--) { ... }

2)底部元素,你称之为'max',应该像这样初始化:

max = arr[n-1];

3)关于第二个循环的相同观察:

for (int i = n-2; i >= x; i--) { ... }

4) 数组的重新分配应该使用操作符delete[]而不是delete. 否则,您将有内存泄漏和未定义的行为。在这里您可以找到有关这些运算符的一些附加信息:

delete[] arr;

推荐阅读