顺序栈
采用动态开辟的数组进行实现
#include <iostream>
#include <string.h>
using namespace std;
class SeqStack
{
public:
SeqStack(int size = 10)
:mtop(0),
mcap(size)
{
mpStack = new int[mcap];
}
~SeqStack()
{
delete[] mpStack;
mpStack = nullptr;
}
public:
//
void push(int val)
{
if(mtop == mcap) // is full ?
{
expand(2 * mcap);
}
mpStack[mtop++] = val;
}
int top() const
{
if(mtop == 0) // is empty?
throw "stack is empty";
return mpStack[mtop - 1]; // 这里下标不能是 mtop--,否则导致取元素时就删除元素了,导致少打一半数据
}
void pop()
{
if(mtop == 0) // is empty?
throw "stack is empty";
--mtop;
}
inline
bool empty() const
{
return mtop == 0;
}
inline
int size() const
{
return mtop;
}
private:
void expand(int size)
{
int *ptmp = new int[size];
memcpy(ptmp, mpStack, mtop * sizeof(int));
delete mpStack;
mpStack = ptmp;
mcap = size;
}
private:
int *mpStack;
int mtop;
int mcap;
};
int main()
{
int arr[] = {12, 4, 5, 99, -2, 28};
SeqStack s;
for(int v : arr)
{
s.push(v);
}
// cout << "size = " << s.size() << endl;
while(!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
}
链式栈
使用嵌套类实现一个链表,并采用头插和头删的方法实现栈的 push
和 pop
方法
#include <iostream>
#include <string.h>
using namespace std;
//
class LinkStack
{
public:
LinkStack()
:size_(0)
{
head_ = new Node; // 用于辅助操作的头结点
}
~LinkStack()
{
Node *p = head_;
while(p != nullptr)
{
head_ = head_->next_;
delete p;
p = head_;
}
}
int top()
{
if(head_->next_ == nullptr)
throw "stack is empty";
return head_->next_->data_;
}
// 头插头删实现栈的逻辑效果
void push(int val)
{
// head_->1
Node *node = new Node(val, head_->next_);
head_->next_ = node;
size_++;
}
// 头删
void pop()
{
if(head_->next_ == nullptr)
throw "stack is empty";
Node *p = head_->next_;
head_->next_ = p->next_;
delete p;
size_--;
}
bool empty() const
{
return head_->next_ == nullptr;
}
int size() const
{
return size_;
}
private:
struct Node
{
Node(int val = 0, Node *next = nullptr)
:data_(val), next_(next)
{}
int data_;
Node *next_;
};
Node *head_;
int size_;
};
int main()
{
int arr[] = {12, 4, 5, 99, -2, 28};
LinkStack s;
for(int v : arr)
{
s.push(v);
}
// cout << "size_ = " << s.size_() << endl;
while(!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
return 0;
}