• 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;
    }
    
  • 相关阅读:
    【GoLang】GoLang map 非线程安全 & 并发度写优化
    【IDEA】IDEA 如何设置编辑器字体大小
    【GoLang】GoLang fmt 占位符详解
    转头条:阿里p7架构师:三年经验应该具备什么样的技能?
    RPC与RMI的区别
    为什么使用消息队列,为什么使用RabbitMQ、springAMQP
    cookie的安全性问题
    solr与mysql数据同步的方案
    springcloud与dubbo对比:
    mybatis与分布式事务的面试
  • 原文地址:https://www.cnblogs.com/fewolflion/p/14948247.html
Copyright © 2020-2023  润新知