Stack is one of the most fundamental data structures, which is based on the principle of Last In Fir

 

输入:

输入:
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;    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值