ps:如果用想要尝试下使用栈来解决问题,可以看看这一篇Leetcode“有效的括号”问题
1.顺序栈
#include<iostream>
using namespace std;
#define maxSize 10
//定义顺序栈
typedef struct {
int data[maxSize];
int top;
}Stack;
//初始化栈
void initStack(Stack& st) {
st.top = -1;
}
//判断栈是否为空
int isEmpty(Stack st) {
if (st.top == -1)
{
return 1;
}
else {
return 0;
}
}
//进栈代码
int push(Stack &st,int x) {
if (st.top==maxSize-1) {
return 0;
}
else
{
++(st.top);
st.data[st.top] = x;
return 1;
}
}
//出栈代码
int pop(Stack &st, int &x) {
if (st.top == -1) {
return 0;
}
else
{
x = st.data[st.top];
--(st.top);
return 1;
}
}
//循环遍历栈,显示元素信息
void show(Stack st) {
for (int i = 0; i < st.top+1; i++)
{
cout << st.data[i] <<" ";
}
cout << endl;
}
int main() {
Stack st;
int x=0;
initStack(st);//初始化栈,设置栈顶指针为-1
push(st, 1);//压入1
show(st);
push(st, 2);//压入2
show(st);
push(st, 3);//压入三
show(st);
pop(st, x);//弹出栈顶元素,并赋值给x
show(st);
return 0;
}
2.链栈
#include<iostream>
using namespace std;
#define maxSize 10
//定义顺序栈
typedef struct LNode {
int data;
struct LNode* next;
}LNode;
//初始化栈
void initStack(LNode *&list) {
list = (LNode*)malloc(sizeof(LNode));
list->next = NULL;
}
//判断栈是否为空
int isEmpty(LNode* list) {
if (list->next==NULL)
{
return 1;
}
else {
return 0;
}
}
//进栈代码
void push(LNode*& list, int x) {
LNode* p;
p = (LNode*)malloc(sizeof(LNode));//初始化新栈节点
p->next = NULL;
p->data = x;
p->next=list->next;//采用头插法将栈顶元素更新
list->next = p;
}
//出栈代码
int pop(LNode* list, int& x) {
LNode* p;
if (list->next==NULL)
{
return 0;
}
p = list->next;
x = p->data;
list->next = p->next;
free(p);
return 1;
}
//循环遍历栈,显示元素信息
void show(LNode* list) {
LNode* p;
p = list->next;
while (p!=NULL)
{
cout << p->data<<" ";
p = p->next;
}
cout << endl;
}
int main() {
LNode* lnode;
int x = 1;
initStack(lnode);
push(lnode, 1);//压入1
show(lnode);
push(lnode, 2);//压入2
show(lnode);
push(lnode, 3);//压入3
show(lnode);
pop(lnode,x);//弹出栈顶元素,并赋值给x
cout << x << endl;
show(lnode);
return 0;
}