zoukankan      html  css  js  c++  java
  • DS:顺序栈

    //seqstack.h

    #ifndef _SEQSTACK_H
    #define _SEQSTACK_H
    
    #define MAXSIZE 1024
    #define INFINITY 65535
    typedef struct
    {
    	int data[MAXSIZE];  // 在结构中定义一个数组
    	int top;            // 指示栈顶元素,在数组中相当于索引
    }SeqStack;
    
    void InitStack(SeqStack* stack);
    int IsEmpty(SeqStack* stack);
    int SeqStack_Top(SeqStack* stack); // 返回栈顶元素
    int SeqStack_Pop(SeqStack* stack); // 出栈(弹出栈顶元素)
    void SeqStack_Push(SeqStack* stack, int val);  // 将元素val压入栈中
    void SeqStack_Destory(SeqStack* stack);       // 销毁栈
    
    #endif // !_SEQSTACK_H
    

    //seqstack.c

    #include "seqstack.h"
    
    void InitStack(SeqStack* stack)
    {
    	stack->top = -1;
    }
    
    int IsEmpty(SeqStack* stack)
    {
    	if (stack->top == -1)
    		return 1;
    	return 0;
    }
    
    int SeqStack_Top(SeqStack* stack)
    {
    	if (!IsEmpty(stack))
    		return stack->data[stack->top];
    	return INFINITY;
    }
    
    int SeqStack_Pop(SeqStack* stack)
    {
    	if (!IsEmpty(stack))
    		return stack->data[stack->top--];
    	return INFINITY;
    }
    
    void SeqStack_Push(SeqStack* stack, int val)
    {
    	if (stack->top >= MAXSIZE - 1)  // stack full
    		return;
    	stack->top++;
    	stack->data[stack->top] = val;
    }
    
    void SeqStack_Destory(SeqStack* stack)
    {
    	if (!IsEmpty(stack))
    		stack = 0;
    		//free(stack);  //这是我注释掉的,它之前并没有malloc(),为何要free()掉?【我写的stack=0】
    }
    

    //main.c

    #include<stdio.h>
    #include<stdlib.h>
    #include"seqstack.h"
    
    int main()
    {
    	srand((unsigned)time(0));
    	SeqStack stack;
    	InitStack(&stack);
    
    	for (int i = 0; i < 50; i++)
    	{
    		SeqStack_Push(&stack, rand() % 1000);
    	}
    
    	printf("栈顶元素:%d
    ", SeqStack_Top(&stack));
    
    	printf("栈中元素:");
    	for (int i = 0; i < 50; i++)
    	{
    		if (i % 5 == 0)    // 每5个元素一行输出
    			printf("
    ");
    		printf("%d ", SeqStack_Pop(&stack));
    	}
    	printf("
    ");
    
    	return 0;
    }
    
  • 相关阅读:
    CEAA自动汇编脚本常用命令
    PIC之拉电流和灌电流
    CHARRANGE 结构
    汇编中的lodsb和stosb、lodsd和stosd指令
    汇编中的STOSB与STOSD指令
    汇编中的CLD指令
    SQL中distinct的用法
    SQL union介绍
    【项目排期】测试排期问题思考
    SQL join的介绍
  • 原文地址:https://www.cnblogs.com/fewolflion/p/14948247.html
Copyright © 2011-2022 走看看