顺序栈


#include<iostream>
using namespace std;

class seqStack
{
public:
	seqStack(int size = 10)
		:mTop(0)
		,mCap(size)
	{
		myStack = new int[mCap];
	};
	~seqStack()
	{
		delete[]myStack;
		myStack = nullptr;
	}
public:
	//入栈
	void push(int val)
	{
		if (mTop == mCap)
		{
			//扩容
			expand(2 * mCap);
		}
		myStack[mTop++] = val;
	}
	//出栈
	void pop()
	{
		if (mTop == 0)
		{
			//return;
			throw "stack is empty";
		}
		mTop--;
	}
	//获取栈顶元素
	int top() const
	{
		if (mTop == 0)
			throw "stack is empty";
		return myStack[mTop - 1];
	}
	//栈空
	bool empty()
	{
		return mTop == 0;
	}
	//栈元素个数
	int size() const
	{
		return mTop;
	}
private:
	void expand(int size)
	{
		int* p = new int[size];
		memcpy(p, myStack, mCap * sizeof(int));
		delete[]myStack;
		myStack = p;
		mCap = size;
	}
private:
	int* myStack;
	int mTop;//栈顶位置
	int mCap;//栈空间大小
};

int main()
{
	int arr[] = { 12,35,7,86,34,85,23 };
	seqStack s;
	for (int v : arr)
	{
		s.push(v);
	}
	while (!s.empty())
	{
		cout << s.top() << " ";
		s.pop();
	}
	cout << endl;
	

	return 0;
}

链式栈


#include<iostream>
using namespace std;

class linkStack
{
public:
	linkStack(int data=0)
	{
		head_ = new Node();
		size_ = 0;
	}
	~linkStack()
	{
		Node* p = head_;
		while (p != nullptr)
		{
			head_ = head_->next;
			delete p;
			p = head_;
		}
	}
public:
	//入栈O(1)——把链表头结点后面,第一个有效结点的位置,当做栈顶位置
	void push(int val)
	{
		Node* node = new Node(val);
		node->next = head_->next;
		head_->next = node;
		size_++;
	}
	//出栈(1)
	void pop()
	{
		if (head_->next == nullptr)
		{
			throw "stack is empty!";
		}
		Node* p = head_->next;
		if (p != nullptr)
		{
			head_->next = p->next;
			delete p;
			size_--;
		}	
	}
	//获取栈顶元素
	int top() const
	{
		if (head_->next == nullptr)
			throw "stack isempty";
		return head_->next->data_;
	}
	//判空
	bool empty() const
	{
		return head_->next == nullptr;
	}
	//返回栈元素个数  O(1)
	int size() const
	{
		return size_;
	}
	
private:
	struct Node
	{
		Node(int data = 0) :data_(data),next(nullptr) {};
		int data_; 
		Node* next;
	};

	Node* head_;
	int size_;
};

int main()
{
	int arr[] = { 12,35,7,86,34,85,23 };
	linkStack s;
	for (int v : arr)
	{
		s.push(v);
	}
	while (!s.empty())
	{
		cout << s.top() << " ";
		s.pop();
	}
	cout << endl;
	

	return 0;
}

括号匹配问题


bool func(string s)
{
	stack<char>st;
	for (char ch : s)
	{
		if (ch == '(' || ch == '[' || ch == '{')
		{
			st.push(ch);
		}
		else
		{
			//只出现一个有括号
			if (st.empty())
				return false;
			//遇到右括号
			int ans = st.top();
			st.pop();
			if (ans == ')' && ch != '('
				|| ans == ']' && ch != '['
				|| ans == '}' && ch != '{')
				return false;
		}
	}
	//栈里的括号是否处理完
	return st.empty();
}

int main()
{
	string s = "}";
	if (func(s))
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}
	return 0;
}

逆波兰表达式求解


class Solution {
public:
    int cal(int left, int right, char sign)
    {
        switch (sign)
        {
        case '+':
            return left + right;
        case '-':
            return left - right;
        case '*':
            return left * right;
        case '/':
            return left / right;
        default:
            break;
        }
        throw "";
    }
    int evalRPN(vector<string>& tokens) {
        stack<int>intStack;
        for (string str : tokens)
        {
            if (str.size() == 1 &&
                (str[0] == '+' || str[0] == '-'
                || str[0] == '*' || str[0] == '/'))
            {
                int right = intStack.top();
                intStack.pop();
                int left = intStack.top();
                intStack.pop();
                intStack.push(cal(left, right, str[0]));
            }
            else
            {
                intStack.push(stoi(str));
            }
        }
        return intStack.top();
    }
   
};

中缀转后缀


#include<iostream>
using namespace std;
#include<stack>
#include<string>
#include<vector>

//比较符号优先级
bool priority(char ch, char topch)
{
	if ((ch == '*' || ch == '/') && ((topch == '+' || topch == '-')))
	{
		return true;
	}
	if (topch == '('&&ch!=')')
	{
		return true; 
	}
	return false;
}
string middleToEndExpr(string expr)
{
	string result;
	stack<char>s;
	for (char ch : expr)
	{
		if (ch >= '0' && ch <= '9')
		{
			result.push_back(ch);
		}
		else
		{
			//处理符号
			while (1)
			{
				if (s.empty() || ch == '(')
				{
					s.push(ch);
					break;
				}
				
				//比较当前符号ch和栈顶符号的优先级
				char topch = s.top();
				//true表示大于栈顶
				if (priority(ch, topch))
				{
					s.push(ch);
					break;
				}
				else
				{
					s.pop();
					if (topch == '(')//如果遇见),一直出栈,直到(
					{
						break;
					}
					result.push_back(topch);
				}
				
			}
		}
	}
	//如果符号栈还存留符号,直接输出到后缀表达式里面
	while (!s.empty())
	{
		result.push_back(s.top());
		s.pop();
	}
	return result;
}

int main()
{
	cout << middleToEndExpr("(1+2)*(3+4)") << endl;
	cout << middleToEndExpr("2+(4+6)/2+6/3") << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值