输入:
输入:
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop
输出:
Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid
#define StackMax 100000
typedef struct stack_array {
unsigned int capacity; // 栈的容量
unsigned int top_of_stack; // 栈顶的下标
unsigned int *array; // 用于存放栈的数组
}stack;
stack create_stack(unsigned int stack_capacity);
void push_stack(stack s, unsigned int data);
void pop_stack(stack s);
void PeekMedian(stack s);
int main()
{
stack stack = create_stack(StackMax);
int topdata, i;
}
/* 创建一个栈 */
stack *create_stack(unsigned int stack_capacity)
{
stack *stack = (stack*)malloc(sizeof(stack));
if (stack == NULL)
printf("malloc error!\n");
stack->array = (int *)malloc(sizeof(unsigned int) * stack_capacity);
if (stack->array == NULL)
printf("malloc error!\n");
stack->capacity = stack_capacity;
return stack;
}
/* PUSH 操作 */
void push_stack(stack s, unsigned int data)
{
if (StackMax <= s->top_of_stack) //栈满
{
return;
}
else
{
s->array[s->top_of_stack] = data;
s->top_of_stack++;
}
}
/* POP 操作 */
void pop_stack(stack s)
{
if(0 == s->top_of_stack) //栈空
{
printf("Invalid\n");
return;
}
else
{
s->top_of_stack--;
printf("%ld\n",s->array[s->top_of_stack]);
}
}
void PeekMedian(stack s)
{
unsigned int index = 0;
if(0 == s->top_of_stack) //栈空
{
printf("Invalid\n");
return;
}
if(0 == (s->top_of_stack%2))
{
index = s->top_of_stack/2;
}
else
{
index = (s->top_of_stack+1)/2;
}
printf("%ld\n",s->array[index]);
return;
}