关于堆栈的一些认识
2016-05-05 21:10
330 查看
特别注意:堆栈是一种先进后出(FILO)的数据类型,最后入栈的数据存放在编号为top-1的地址单元,也就是说,编号为top-1的地址单元存放的是最后入栈的数据,编号为top的单元永远都不会存数据。
#include <iostream> #include <string> #include "stack.h" /***** * 关于堆栈的一点认识:设堆栈占用size个地址单元,但堆栈为空时,top=0,有一个元素时,top=1,数据放在编号为0的地址单元,以此类推,当堆栈满时,size=top * 因此:数据入栈时,先是将数据放到编号为top的单元(编号从0开始),然后top自加1 * 数据出栈时,现将top自减1,然后数据出栈。编号为top的地址单元始终都没有数据 ****/ Stack::Stack(int n) { size = n; pitems = new Item [size]; top = 0; } Stack::Stack(const Stack &st) //复制构造函数 { pitems = new Item[st.size]; size = st.size; top = 0; for(int i=0;i<st.top;i++) { pitems[i] = st.pitems[i]; // size++; top++; } } Stack::~Stack() { delete [] pitems; } //空代表没有初始化堆栈,top=0 bool Stack::isempty() const { return (top ? false:true); } //堆栈满表示:top=size bool Stack::isfull() const { return (top == size)? true:false; } bool Stack::push(const Item & item) { if(top == size) return false; else { pitems[top] = item; top = top+1; return true; } } bool Stack::pop(Item & item) { if(top == 0) return false; else { top--; item = pitems[top]; return true; } } Stack & Stack::operator=(const Stack & st) //深度赋值 { if(this == & st) //& 取地址 return *this; else { delete [] pitems; pitems = new Item [st.size]; size = 0; top = 0; for(int i=0;i<st.size;i++) { pitems[i] = st.pitems[i]; size++; top++; } return *this; } } std::ostream & operator<<(std::ostream & os, const Stack & st) { for(int i=0;i<st.top;i++) { os << st.pitems[i] << "\n"; } return os; }
相关文章推荐
- Android Volley增加Https支持,允许SSL
- linux添加用户、权限
- 克隆或复制VMware虚拟机时的网络设置
- JAVA——集合类
- NYOJ 题目860 又见01背包
- 高斯图像滤波原理及其编程离散化实现方法
- memcache简介以及使用方法
- 斜率dp
- 20.从上往下打印二叉树
- excel中以文本形式保存长数字
- 错误检查
- 面向对象五大原则之一:单一职责原则
- 搭建ARM DS-5 STREAMLINE
- Getting Spring Error “Bean named 'x' must be of type [y], but was actually of type [$Proxy]” in Jenk
- POJ 2255 Tree Recovery && Ulm Local 1997 Tree Recovery (二叉树的前中后序遍历)
- Reddit网站获赞最高文章/评论的爬取
- ZOJ 3869-Ace of Aces【模拟众数】
- 【深入理解JVM】:Class类文件结构
- 10474 - Where is the Marble?
- STM32_外部中断(寄存器版)_笔记