题目:
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Stack
{
int* data;
int top;//栈顶元素坐标
int capacity;//栈的容量
}ST;
void STInit(ST* ps)
{
ps->data = NULL;
ps->top = 0;//ps->top=-1;
//初始化时top给0,意味着top指向栈顶数据的下一个
//初始化时top给1,意味着top指向栈顶数据
ps->capacity = 0;//初始化容量给0
}
void StackPush(ST* ps, int x)//压栈/入栈操作
{
if (ps->capacity == ps->top)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//三目操作符
//如果ps->capacity等于0,那么就给4个字节的空间,如果不等于0就扩容两倍
int* tmp = (int*)realloc(ps->data, sizeof(int)*newCapacity);
if (tmp == NULL)//扩容失败退出程序
{
exit(-1);
}
ps->capacity = newCapacity;//把capacity换成新的
ps->data = tmp;//data也指向新的空间
}
ps->data[ps->top] = x;
ps->top++;
}
void STCreate(ST* ps, int m)
{
int x = 0;
while (m)
{
scanf("%d", &x);
getchar();
StackPush(ps, x);
m--;
}
}
void STPop(ST* ps, int n)//删除栈顶元素操作
{
while (n)
{
ps->top--;
n--;
}
}
int main()
{
ST List;
STInit(&List);//栈的初始化
int m = 0;
scanf("%d", &m);//输入元素个数
getchar();
STCreate(&List, m);//创建栈
int n = 0;
scanf("%d", &n);//出栈次数输入
getchar();
STPop(&List, n);
if (List.top <= 0)//如果top<=0,说明此时已经是一个空栈
{
printf("-1");//打印-1
}
else
{
printf("%d", List.data[List.top - 1]);
//如果不是空栈,注意要打印top是栈顶的下一个元素,所以要减1,打印栈顶的元素
}
return 0;
}