栈的应用(C++,进制转化、括号匹配)

         十进制转化八进制,利用栈

#include//十进制转八进制,利用栈
using namespace std;
typedef struct stack
{
	int data;
	stack* next;
}stack, * linkstack;
void Initstack(linkstack& s)
{
	s = NULL;
}
int Emptystack(linkstack s)
{
	if (s == NULL)
		return 1;
	else
		return 0;
}
void Pushstack(linkstack& s, int node)
{
	linkstack p = new stack;
	p->data = node;
	p->next = s;
	s = p;
}
int Popstack(linkstack& s, int& node)
{
	linkstack p = new stack;
	if (s == NULL) return 0;
	node = s->data;
	p = s;
	s = s->next;
	delete p;
	return 1;
}
void Conversion(int N)
{
	linkstack s;
	Initstack(s);
	while (N)
	{
		Pushstack(s, N % 8);
		N = N / 8;
	}
	while (!Emptystack(s))
	{
		int e;
		Popstack(s, e);
		cout << e;
	}
}
int main()
{
	int N;
	cin >> N;
	cout << "八进制:" << endl;
	Conversion(N);
}

  栈的应用(C++,进制转化、括号匹配)_第1张图片

       括号匹配 

#include//括号匹配,利用栈
using namespace std;
typedef struct stack
{
	int data;
	stack* next;
}stack,*linkstack;
void Initstack(linkstack &s)
{
	s = NULL;
}
int Emptystack(linkstack s)
{
	if (s == NULL)
		return 1;
	else
		return 0;
}
void Pushstack(linkstack& s, char node)
{
	linkstack p=new stack;
	p->data = node;
	p->next = s;
	s = p;
}
int Popstack(linkstack& s, char &node)
{
	linkstack p = new stack;
	if (s == NULL) return 0;
	node = s->data;
	p = s;
	s = s->next;
	delete p;
	return 1;
}
int Gettop(linkstack s)
{
	if (s != NULL)
		return s->data;
}
int Matching()//返回一合法、返回零不合法
{
	linkstack s;
	Initstack(s);
	int flag = 1;
	char ch,x;
	cin >> ch;
	while (ch != '#' && flag)
	{
		switch (ch)
		{
		case '[':
		case '(':
			Pushstack(s, ch);//左括号入栈
			break;
		case ')':
			if (!Emptystack(s) && Gettop(s) == '(')
				Popstack(s, x);//栈非空且栈顶是(,匹配成功;(出栈
			else flag = 0;//栈空或栈顶不是(,匹配失败
			break;
		case ']':
			if (!Emptystack(s) && Gettop(s) == '[')
				Popstack(s, x); //栈非空且栈顶是[, 匹配成功;[出栈
			else flag = 0;//栈空或栈顶不是(,匹配失败
			break;
		}
		cin >> ch;
	}
	if (Emptystack(s) && flag) return 1;
	else return 0;
}
int main()
{
	int a=Matching();
	cout << a;
}

 栈的应用(C++,进制转化、括号匹配)_第2张图片

你可能感兴趣的:(算法,数据结构)