1、基于数组实现
#include <iostream>
using namespace std;
//数组实现栈
//理想的实现是创建一个名为Stack的类
#define MAX_SIZE 101
int A[MAX_SIZE];
int top = -1;
void Push(int x)
{
if (top == MAX_SIZE - 1)//处理溢出情况
{
cout << "Error: stack overflow!" << endl;
return;
}
top++;
A[top] = x;
//A[++top] = x;自增会发生在赋值之前
}
void Pop()
{
if (top == -1)
{
cout << "Error: No element to pop!" << endl;
return;
}
top--;
}
int Top()
{
return A[top];
}
int IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
void Print()
{
int i;
cout << "Stack: ";
for (i = 0; i <= top; i++)
cout << A[i] << " ";
cout << endl;
}
int main()
{
Push(2);
Push(5);
Push(10);
Print();
Pop();
Print();
Push(12);
Print();
system("pause");
return 0;
}
2、基于链表实现
//链表实现栈
class Node
{
public:
int data;
Node* link;
};
Node* top = NULL;
void Push(int x)
{
Node* temp = new Node();
temp->data = x;
temp->link = top;
top = temp;
}
void Pop()
{
Node *temp;
if (top == NULL)
return;
temp = top;
top = top->link;
free(temp);
}
3、反转字符串
#include <iostream>
#include <stack>
using namespace std;
//反转字符串
void Reverse(char C[], int n)
{
stack<char> S;//创建字符栈
//loop for push
for (int i = 0; i < n; i++)
{
S.push(C[i]);
}
//loop for pop
for (int i = 0; i < n; i++)
{
C[i] = S.top();
S.pop();
}
}
int main()
{
char C[51];
cout << "Enter a string: ";
cin >> C;
Reverse(C, strlen(C));
cout << "Output = " << C;
system("pause");
return 0;
}
反转链表
//反转链表
void Reverse()
{
if (head == NULL)
return;
stack<Node*> S;
Node* temp = head;
while (temp != NULL)
{
S.push(temp);
temp = temp->next;
}
temp = S.top();
head = temp;
S.pop();
while (!S.empty())
{
temp->next = S.top();
S.pop();
temp = temp->next;
}
}
5、检查括号匹配性
#include<iostream>
#include<stack>
using namespace std;
bool Check(char C[],int n)
{
stack<char> S;
for (int i = 0; i < n; i++)
{
if (C[i] == '(' || C[i] == '{' || C[i] == '[')
S.push(C[i]);// C[i]入栈
else if (C[i] == ')' || C[i] == '}' || C[i] == ']')
{
if (S.empty())//右括号前面没有左括号
return false;
else if ((S.top() == '('&&C[i] == ')') || (S.top() == '{'&&C[i] == '}') || (S.top() == '['&&C[i] == ']'))
S.pop();
else//右括号与栈顶的左括号不匹配
return false;
}
}
return S.empty() ? true : false;
}
int main()
{
char C[51];
cout << "Enter a string: ";
cin >> C;
bool flag = Check(C, strlen(C));
if (flag)
cout << "Balance" << endl;
else
cout << "Not Balance" << endl;
system("pause");
return 0;
}
6、前缀、中缀和后缀
基于栈实现中缀转后缀