一、顺序栈的实现
#include<iostream>
using namespace std;
//顺序栈 C++容器适配器 stack push pop top empty size
class SeqStack
{
public:
SeqStack(int size = 10)
:top(0)
, cap(size)
{
pStack = new int[cap];
}
~SeqStack()
{
delete[] pStack;
pStack = nullptr;
}
public:
//入栈
void push(int val)
{
if (top == cap)
{
//栈扩容
expand(2 * cap);
}
pStack[top++] = val;
}
//出栈
void pop()
{
if (top == 0)
{
throw "stack is empty!";
}
top--;
}
//获取栈顶元素
int Top() const
{
if (top == 0)
{
throw "stack is empty!";
}
return pStack[top - 1];
}
//栈空
bool empty()const
{
if (top == 0)
{
return true;
}
return false;
}
//计算个数
int size()const
{
return top;
}
private:
void expand(int size)
{
int* p = new int[size];
memcpy(p, pStack, top * sizeof(int));
delete[] pStack;
pStack = p;
cap = size;
}
private:
int* pStack;
int top; //栈顶位置
int cap; //栈空间大小
};
int main() {
int arr[] = { 12,4,56,7,89,31,53,75 };
SeqStack s;
for (int v : arr)
{
s.push(v);
}
while (!s.empty())
{
cout << s.Top() << " ";
s.pop();
}
cout << endl;
return 0;
}
二、链栈的实现
#include<iostream>
using namespace std;
//链式栈
class LinkStack
{
public:
LinkStack()
{
head = new Node;
msize = 0;
}
~LinkStack()
{
Node* p = head;
while (p != nullptr)
{
head = head->next;
delete p;
p = head;
}
}
public:
//入栈操作 把链表头节点后面,第一个有效节点的位置,当作栈顶位置
void push(int val)
{
Node* node = new Node(val);
node->next = head->next;
head->next = node;
msize++;
}
//出栈操作
void pop()
{
if (head->next == nullptr)
{
throw "stack is empty!";
}
Node* p = head->next;
head->next = p->next;
delete p;
msize--;
}
//获取栈顶元素
int top()const
{
if (head->next == nullptr)
{
throw "stack is empty!";
}
return head->next->data;
}
//判断栈是否为空
bool empty()const
{
return head->next == nullptr;
}
//返回栈元素个数 遍历一遍链表,记录节点个数O(n)
int size()const
{
return msize;
}
private:
struct Node
{
Node(int data=0):data(data),next(nullptr){}
int data;
Node* next;
};
Node* head;
int msize;
};
int main() {
int arr[] = { 12,4,56,7,89,31,53,75 };
LinkStack s;
for (int v : arr)
{
s.push(v);
}
cout << s.size() << endl;
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
cout << s.size() << endl;
return 0;
}
总结
今天主要给大家写了一个栈的数据结构,分别为顺序栈和链栈。栈的特点就是先入后出。