栈(Stack)
限定仅在表尾进行插入和删除的线性表
读完数据结构栈模型后,按照抽象数据模型实现一部分栈的功能,代码如下
1 顺序存储结构
//2021/03/10H:\图解数据结构算法\栈\栈.vcxproj
#include <iostream>
using namespace std;
//顺序栈
#define MAXSIZE 10
typedef bool Status;
class SqStack
{
public:
SqStack()
{
top = -1;
}
//push 操作
Status SqPush(int num)
{
if (top == MAXSIZE -1)
{
return false;
}
top++;
this->elem[top] = num;
return true;
}
//pop 操作
Status SqPop(int *num)
{
if (top == -1)
{
return false;
}
*num = this->elem[top];
top--;
return true;
}
//GetTop,返回给e
Status GetTop(int* e)
{
if (top == -1)
{
return false;
}
*e = elem[top];
}
//返回栈的元素
int GetLength()
{
return top + 1;
}
private:
int top; //栈顶指针
int elem[MAXSIZE]; //元素
};
//测试代码
int main()
{
SqStack sq;
for (int i = 0; i < 10; i++)
{
sq.SqPush(i);
}
int num = 0;
sq.GetTop(&num);
cout << "top元素为:" << num << endl;
cout << "元素个数为:" << sq.GetLength() << endl;
sq.SqPop(&num);
cout << "pop元素为:" << num << endl;
cout << "元素个数为:" << sq.GetLength() << endl;
cout << "hello world!" << endl;
system("pause");
return 0;
}
输出
2 链式存储结构
//2021/03/10H:\图解数据结构算法\栈\栈.vcxproj
#include <iostream>
using namespace std;
#define MAXSIZE 10
typedef bool Status;
typedef int ElemType;
//要实现链栈首先定义结点
typedef struct StackNode
{
//数据域
ElemType my_data;
//指针域
struct StackNode* my_next;
}StackNode, *LinkStackPtr;
//定义链栈
class LinkStack
{
public:
//构造函数
LinkStack()
{
top = NULL;
count = 0;
}
//析构函数,依次删除链栈内的结点
~LinkStack()
{
if (top == NULL)
{
count = 0;
}
else
{
LinkStackPtr t;
while (top != NULL)
{
t = this->top;
this->top = this->top->my_next;
free(t);
}
}
}
//push 操作
Status SqPush(int num)
{
LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode));
if (s == NULL)
{
return false;
}
s->my_data = num;
s->my_next = this->top;
this->top = s;
count++;
return true;
}
//pop出栈
Status SqPop(int *num)
{
if (count == 0)
{
return false;
}
LinkStackPtr t;
t = this->top;
*num = t->my_data;
this->top = this->top->my_next;
free(t);
count--;
return true;
}
//返回长度
int GetLength()
{
return count;
}
//取得顶部元素GetTop,返回给e
Status GetTop(int* e)
{
if (count == 0)
{
return false;
}
*e = this->top->my_data;
}
private:
LinkStackPtr top; //指向链表结点的指针
int count;
};
//与顺序存储结构相同得测试代码,体现了封装之美
int main()
{
LinkStack sq;
for (int i = 0; i < 10; i++)
{
sq.SqPush(i);
}
int num = 0;
sq.GetTop(&num);
cout << "top元素为:" << num << endl;
cout << "元素个数为:" << sq.GetLength() << endl;
sq.SqPop(&num);
cout << "pop元素为:" << num << endl;
cout << "元素个数为:" << sq.GetLength() << endl;
cout << "hello world!" << endl;
system("pause");
return 0;
}
输出
顺序栈和链栈的对比
- 栈的两种存储结构的push和pop操作时间复杂度均为O(1)
- 顺序栈需要事先确定一个固定长度,可能造成内存空间上的浪费
- 链栈的每个元素有指针域,也有一部分内存开销,但是链栈可以不定长