栈的链表形式
#include <cstdio>
using namespace std;
#define null NULL
struct node{
node* nxt;
int val;
};
struct stack{
node* head;
int siz;//链表长度
stack() //构造函数,初始化
{
head = new node();
siz = 0;
void push(int val)
{
// head -> nodex -> nodex-1 -> ... ->NULL
node* cur = new node();
cur->val =val;
cur->nxt = head->nxt;
head->nxt = cur;
siz++;
}
void pop()
{
// head -> top(nodex) -> nodex-1 -> ... ->NULL
node* top = head->nxt;
head->nxt = top->nxt;
delete top;
siz--;
}
int top()
{
// head -> top(nodex) -> nodex-1 -> ... ->NULL
if(siz > 0)//如果链表不为空,则返回栈顶元素
{
return head->nxt->val;
}
else
{
// error
return 0;
}
}
int size()
{
return siz;
}
bool empty()
{
return siz == 0;
}
int main()
{
stack st = stack();
st.push(1);
st.push(2);
st.pop();
st.push(3);
st.push(10);
st.push(5);
st.pop();
st.push(9);
//9 10 3 1
while(!st.empty())
{
int cur = st.top();
st.pop();
printf("%d\n",cur);//输出结果为 9 10 3 1
}
}
栈的数组形式
#include <cstdio>
#define null NULL
using namespace std;
struct stack
{
int* st;
int _top;
int siz;
int maxSiz;
stack(int msiz)
{
// st st+1 st+2 .... st+9 st+10
// 1000 1001 1002 1003 ... 1009 1010
// _bottom _top
st = new int[msiz];// int st[10];
_top = 0;
siz = 0;
maxSiz = msiz;
}
void push(int val)
{
if(siz == maxSiz)
{
printf("stack is full\n");
return;
}
_top = (_top + 1) % maxSiz;
st[_top] = val;
siz++;
}
int top()
{
return st[_top];
}
void pop()
{
_top = (_top - 1 + maxSiz) % maxSiz;
siz--;
}
bool empty()
{
return siz == 0;
}
};
int main()
{
stack st = stack(10);
st.push(1);
st.push(2);
st.pop();
st.push(3);
st.push(10);
st.push(5);
st.pop();
st.push(9);
while(!st.empty())
{
int x =st.top();
st.pop();
printf("%d\n",x);//输出结果为9 10 3 1
}
}