数据结构与算法之栈
文章目录
栈
栈是一种先进后出的数据结构。
注意:在c++的STL标准库中已经实现了栈这种数据结构,而STL标准库中栈的底层是由双端队列(deque)实现的,所以在STL标准库中栈不算一种容器,而是一种适配器。
#栈示意图如下所示:
元素只能在一端进出,所以最先入栈的元素最后才能出栈,最后入栈的元素最先出栈。
栈的实现
栈可以用链表实现也可以用数组实现
本文中将分别用两种方式实现栈。
1.用链表实现栈
用链表实现栈就不需要像数组一样考虑栈满的问题,只要内存足够大就行。
类结构如下:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class MyStack{
public:
MyStack(): s(0), dummy(new ListNode(0)){ }
~MyStack();
bool empty() { return s == 0; } //判断栈是否为空
void push(int value); //将元素入栈
void pop(); //将栈顶元素出栈
int top() const;//将返回栈顶元素
int size() const{ return s; } //返回栈中元素个数
private:
ListNode* dummy; //虚头结点
int s; //统计栈中元素个数
};
(1)元素入栈操作
void MyStack::push(int value){
ListNode* newNode = new ListNode(value);
newNode->next = dummy->next;
dummy->next = newNode;
s++;
}
(2)元素出栈
void MyStack::pop(){
if(s == 0)
return;
ListNode* deleteNode = dummy->next;
dummy->next = dummy->next->next;
delete deleteNode;
s--;
}
(3)返回栈顶元素值(必须确保栈不为空)
int MyStack::top() const{
return dummy->next->val;
}
2.用数组实现栈
类结构如下:
class MyStack{
public:
MyStack(int n = 10); //默认初始化数组容量为10
~MyStack();
bool empty() { return index == -1; }//判断栈是否为空
void push(int value); //将元素入栈
void pop(); //将栈顶元素出栈
int top() const { return data[index]; }//将返回栈顶元素(前提栈不为空)
int size() const { return index + 1; } //返回栈中元素个数
private:
void changeLength(int oldLength); //对数组扩容
int* data; //虚头结点
int index; //栈顶元素下标
int capacity;
};
(1)构造函数
MyStack::MyStack(int n){
data = new int[n];
index = -1;
capacity = n;
}
(2)析构函数
MyStack::~MyStack(){
delete [] data;
data = nullptr;
}
(3)元素入栈
void MyStack::push(int value){
if(index == capacity){
changeLength(capacity); //扩容
}
data[++index] = value;
}
(4)元素出栈
void MyStack::pop(){
if(index == -1)
return;
--index;
}
(5)对数组扩容
void MyStack::changeLength(int oldLength){
capacity = oldLength * 2;
int* temp = new int [capacity];
for(int i = 0; i < oldLength; ++i){
temp[i] = data[i];
}
delete [] data;
data = temp;
}