Maximum Element
您有一个空序列,并且将向您提供 N 个查询。每个查询都是以下三种类型之一:
1 x - 将元素 x 压入堆栈。
2 - 删除堆栈顶部的元素。
3 - 打印堆栈中的最大元素。
输入格式
输入的第一行包含一个整数 N。接下来的 N 行每行包含一个上述查询。 (保证每个查询都是有效的。)
约束
1≤N≤105
1≤x≤109
1≤类型≤3
输出格式
对于每个类型 3 查询,在新行中打印堆栈中的最大元素。
示例输入
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
示例输出
26
91
My Code is:
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100000
long a[MAX_SIZE];
int top = -1;
int Push(long x){
if(top == MAX_SIZE-1){
}
top++;
a[top] = x;
return 0;
}
int Pop(){
if(top == -1){
}
top--;
return 0;
}
int Print(){
int i;
for(i=0;i<top+1;i++){
printf("%ld\n",a[i]);
}
return 0;
}
int main(){
long i, x;
int n, t;
scanf("%d",&t);
for(i=0;i<t;i++){
scanf("%d",&n);
switch(n){
case 1 :
scanf("%ld",&x);
Push(x);
break;
case 2 :
Pop();
break;
case 3 :
Print();
break;
}
}
}
My Output are: Nice try, but you did not pass this test case. Input (stdin)
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
Your Output (stdout)
26
26
91
Expected Output
26
91
Compiler Message
Wrong Answer
最佳答案
发布的代码的主要问题是 Print()
函数打印所有内容,而不是遵循它应该只打印当前堆栈上的最大值的约束。
给出发布的代码,对其进行一些清理并修复 Print()
函数并使用有意义的变量名称并使用垂直和水平间距以提高可读性:
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE (105)
// prototypes
void Print( void );
void Pop( void );
void Push( int value );
int stack[ MAX_STACK_SIZE ];
int stackIndex = -1;
enum action {pushValue=1, popValue=2, printMax=3};
int main( void )
{
int value;
int numEntries;
enum action myAction;
// get number of entries range 1...105
scanf("%d",&numEntries);
for( int i=0; i<numEntries; i++ )
{
// get action range 1...3
scanf("%d", (int*)&myAction);
switch( myAction )
{
case pushValue :
// get value range 1...109
scanf("%d",&value);
Push( value );
break;
case popValue :
Pop();
break;
case printMax :
Print();
break;
} // end switch
} // end for
return 0;
} // end function: main
void Push(int value)
{
stackIndex++;
stack[stackIndex] = value;
}
void Pop()
{
if( 0 <= stackIndex)
{ // then stack not empty
stackIndex--;
}
}
void Print()
{
int maxValue = -1;
int i;
for( i = 0; i<= stackIndex; i++ )
{
if( stack[i] > maxValue )
{
maxValue = stack[i];
}
}
if( -1 != maxValue )
{
printf("%d\n", maxValue);
}
}
根据已发布的输入,有一个输出。
26
91
关于c - 我的代码无法正常工作,我做错了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839391/