顺序栈
栈特点
先进后出,后进先出。
栈顶指针:top指向栈顶元素,top=0表示栈是空的;
入栈:arr[top]=1,top++;
出栈:top–;
访问栈顶元素:arr[top-1];
栈满:top = sizeof(arr)/sizeof(arr[0])
实现:可以用数组实现,也可以用链表实现,只是规定了数组或链表的进出顺序。
C++stack容器: stack就是栈,常用的方法:stack push pop top empty size
#include <iostream>
using namespace std;
// stack push pop top() e,empty()
class SeqStack
{
SeqStack(int size = 10):mCap(size),mCount(0),top(0)
{
Arr = new int[size];
}
~SeqStack()
{
delete [] Arr;
}
public:
void push(int val)
{
if (top == mCap)
{
expand();
}
Arr[top++] = val;
mCount ++;
}
void pop()
{
if (top == 0)
throw "err !";
top--;
mCount--;
}
// top()返回栈顶
int top()
{
if(top == 0)
throw "err !";
return Arr[top - 1];
}
// empty()
bool empty()
{
return top == 0;
}
void GetSize()
{
return mCount;
}
void show() const
{
for (int i = top-1; i >= 0 ; i++)
{
cout << Arr[i] ;
}
cout << endl;
}
private:
int mCap; // zhan rongliang
int mCount; //
int *Arr;
int top;
private:
void expand(int size)
{
int *p = new int[size];
memcpy(p,Arr,sizeof(int) * mCap)
delete Arr;
Arr = p;
mCap = size;
}
};
int main()
{
SeqStack s;
int arr[1,2,3,4,5];
for (int a : arr)
{
s.push(a);
}
s.show();
s.push(6);
s.show();
system("pause");
return 0;
}
链栈
也可以用链表实现栈,入栈可以用头插实现,出栈可以用头删表示。
class LinkStack
{
public:
LinkStack()
{
head_ = new Node;
size_ = 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;
size_++;
}
// 出栈
void pop()
{
if (head_->next_ == nullptr)
{
throw "stack is empty!";
}
Node *p = head_->next_;
head_->next_ = p->next_;
delete p;
size_--;
}
// 获取栈顶元素
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 size_;
}
private:
struct Node
{
Node(int data = 0) : data_(data), next_(nullptr) {}
int data_;
Node *next_;
};
Node *head_;
int size_;
};
int main()
{
int arr[] = { 1,2,3,4,5,6 };
LinkStack s;
for (int v : arr)
{
s.push(v);
}
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
system("pause");
return 0;
}