文章目录
栈和队列都是线性结构(线性表),特殊性在于栈与队列的 基本操作是线性表操作的子集,是操作受限的线性表,称为限定性的数据结构。
线性表 | 栈 |
---|---|
逻辑结构:一对一 | 逻辑结构:一对一 |
存储结构:顺序表、链表 | 存储结构:顺序栈、链栈 |
运算规则:随机存取 | 运算规则:先进后出LIFO |
栈:stack
先进后出的线性表
- 定义:限定仅在表尾进行插入或删除操作的线性表,表尾称为栈顶,表头称为栈底,不含元素的空表称为空栈。
顺序栈
顺序栈,即栈的顺序存储结构是利用一组地址连续的存储单元一次存放自栈底到栈顶的数据元素,同时设置指针top指示栈顶元素在顺序栈中的位置。
top指针的位置是没有数据元素
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<assert.h>
#define SIZE 100
#define TRUE 1
#define OK 1
#define ERROR 0
#define OVERFLOW -2 //超出
#define FALSE 0
#define INCSIZE 2
#define NULLPTR -3
typedef int ElemType;
typedef int Status; //状态
using namespace std;
class SeqStack //只能从尾部插入删除
{
private:
ElemType* top; //栈顶指针
ElemType* base; //栈底指针
int stacksize; //容量
public:
SeqStack()
{
cout << "SeqStack()" << endl;
base = (ElemType*)malloc(sizeof(ElemType) * SIZE);
if (NULL == base) return ;
top = base;
stacksize = SIZE;
}
~SeqStack()
{
cout << "~SeqStack()" << endl;
free(base);
base = NULL;
top = NULL;
stacksize = 0;
}
void Clear() //所有数据元素
{
top = base;
}
bool IsEmpty()
{
return GetSize() == 0; //return top == base;
}
bool IsFull()
{
return GetSize() == SIZE;
}
int GetSize()
{
return (ElemType)(top - base); //算头不算尾
}
Status Push(ElemType val)
{
if (IsFull() && !IncSize())
{
return ERROR;
}
*top = val;
top+=1;
return OK;
}
bool IncSize() //满-》扩容
{
int total = stacksize * INCSIZE;
ElemType* newdata = (ElemType*)realloc(base, total);
if (NULL == newdata)
{
return FALSE;
}
base = newdata;
top = base + stacksize;
return TRUE;
}
Status Pop(ElemType* p) //取出数据并删除
{
if (IsEmpty())
{
return ERROR;
}
if (p == NULL)return NULLPTR;
*p = *(top-1); //top指向的位置没有数据 所以要取它下一个位置的数据
top-=1;
return OK;
}
Status GetTop(ElemType* p) //只取栈顶数据不删除
{
if (IsEmpty())
{
return ERROR;
}
if (p == NULL)return NULLPTR;
*p = *(top-1);
return OK;
}
};
int main()
{
SeqStack s;
int a;
ElemType val;
for (int i = 0; i < 5; i++)
{
cin >> a;
s.Push(a);
}
while (!s.IsEmpty())
{
s.Pop(&val);
cout << val << endl;
}
return 0;
}
链栈
typedef struct StackNode
{
ElemType data;
StackNode* next;
}StackNode,*PStackNode;
class LinkStack
{
private:
StackNode* top;
int cursize;
public :
LinkStack()
{
top = BuyNode();