《数据结构》二、栈

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、前缀、中缀和后缀

基于栈实现中缀转后缀

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值