• C++数据结构之Stack(栈)


    stack,栈,是好比堆积木似的数据结构,从上之下堆积,取出时按“LIFO”-last int first out后进先出的规则。栈一般为线程所独有,也就是每个线程有其自有的栈,与heap堆一般为共有的不同(heap为进程所用,stack为线程所用?)。

    stack主要有四种操作:empty判断栈是否为空;pop将栈顶的元素清除;top显示栈顶的元素(不是取走);push压栈,向栈内增加一个元素。


    代码(在eclipse运行通过):

    .h头文件

    #ifndef STACK
    #define STACK
    
    const int maxstack = 10;
    enum Error_code {overflow, underflow, success};
    typedef int Stack_entry;
    
    class Stack
    {
    public:
    	Stack();
    	bool empty()const;
    	Error_code pop();
    	Error_code top(Stack_entry &item)const;// item作为取出值的载体
    	Error_code push(const Stack_entry &item);// item是放入的值
    private:
    	int count;
    	Stack_entry entry[maxstack];
    };
    
    
    
    #endif /* STACK_ */

    .cpp实现文件
    #include "Stack.h"
    
    Stack::Stack()
    {
    	count = 0;
    }
    bool Stack::empty()const
    {
    	if(count == 0)
    		return true;
    	else
    		return false;
    }
    Error_code Stack::pop()
    {
    	if(empty())
    		return underflow;
    	else
    		count--;
    	return success;
    }
    Error_code Stack::top(Stack_entry &item)const
    {
    	if(count == 0)
    		return underflow;
    	else
    		item = entry[count - 1];
    	return success;
    }
    Error_code Stack::push(const Stack_entry &item)
    {
    	if(count >= maxstack)
    		return overflow;
    	else
    		entry[count++] = item;
    		// firstly make entry[count] = item,later count + 1
    	return success;
    }

    main主程序测试文件:

    #include "Stack.h"
    #include <cstdio> // or: #include "stdio.h"
    //using
    int main()
    {
    	Stack mystack;
    	mystack.push(2);
    	int a;
    	mystack.top(a);
    	printf("%s %d","LvLang",a);
    
    	return 0;
    }

    代码中有一点重要的知识点,就是变量类型模板(不知道专业术语自己扯了这词)Stack_entry,这里的变量类型相当于一个模板,要能运行,必须先实例化这个模板,解决方法是用“typedef”(类型定义),比如:typedef char Stack_entry,这里就将Stack_entry实例化为char变量类型。
  • 相关阅读:
    Linux下安装FTP服务(Ubuntu)
    Ubuntu下无法使用Secure_CRT连接服务器
    Mysql 锁机制
    PHP提取HTML代码中img标签下src属性
    Mysql 隐式转换
    PHPExcel在TP下使用
    ThinkPHP同时操作多个数据库
    PHP 时间相关操作
    ThinkPHP输入验证和I方法使用
    ThinkPHP模板内使用U方法
  • 原文地址:https://www.cnblogs.com/lvlang/p/10586523.html
Copyright © 2020-2023  润新知