Text Reverse(hdu 1062)


题目大意

翻转输出字符串

解题思路

对每个单词字符串进行翻转,考虑入栈当检测到空格时出栈输出,循环直到全部输出。利用栈先进后出实现翻转。

STL
#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	cin>>n;
	getchar();
	while(n--){
		string s;
		getline(cin,s);
		stringstream token(s);
		while(token>>s){
			stack<char>st;
			for(auto&ch:s){
				st.push(ch);
			}
			while(!st.empty()){
				cout<<st.top();
				st.pop();
			}
			cout<<" ";
		}
		cout<<endl;
	}
	return 0;
}
手写栈
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
struct mystack{
	char a[N];
	int t=0;
	void push(char x){
		a[++t]=x;
	}
	void pop(){
		t--;
	}
	char top(){
		return a[t];
	}
	bool empty(){
		return t==0;
	}
};
int main(){
	int n;
	string s;
	cin>>n;
	getchar();
	while(n--){
		getline(cin,s);
		stringstream token(s);
		while(token>>s){
			mystack st;
			for(auto&ch:s){
				st.push(ch);
			}
			while(!st.empty()){
				cout<<st.top();
				st.pop();
			}
			cout<<" ";
		}
		cout<<endl;
	}
	return 0;
}

向右看齐(洛谷P2947)


题目大意

对于序列a,对每个元素输出大于当前元素的右侧最近(从1开始)下标值,不存在输出0。

解题思路

将a中元素从后向前入栈,对每个元素,若栈顶元素值小于等于当前值则出栈(在逻辑上不影响题目求解),若出栈直到为空,则输出0,反之输出栈顶元素。

未知的代码
#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<int>h(n),ans(n);
    for(auto&it:h)cin>>it;
    stack<int>s;
    for(int i=n-1;i>=0;i--){
        while(!s.empty()&&h[s.top()-1]<=h[i])s.pop();
        if(s.empty())ans[i]=0;
        else ans[i]=s.top();
        s.push(i+1);
    }
    for(auto&it:ans)cout<<it<<endl;
    return 0;
}

双栈实现队列(力扣 232)


题目大意

使用两个栈存储队列数据,并实现队列先进先出的特性。

解题思路

一个栈做输入栈,一个做输出栈。数据先存入输入栈,当需访问队头或出队时,先对输出栈操作,若输出栈为空则先将输入栈内容存入输出栈。

未知的代码
class MyQueue {
public:
    MyQueue() {

    }
    
    void push(int x) {
        s1.push(x);
    }
    
    int pop() {
        if(s2.empty()){
            while(!s1.empty()){
            s2.push(s1.top());
            s1.pop();
            }
        }
        int ans=s2.top();
        s2.pop();
        return ans;
    }
    
    int peek() {
        if(s2.empty()){
            while(!s1.empty()){
            s2.push(s1.top());
            s1.pop();
            }
        }
        return s2.top();
    }
    
    bool empty() {
        return s1.empty()&&s2.empty();
    }
private:
    stack<int>s1,s2;
};
posted @ 2023-12-27 12:57  Lost-in-love  阅读(4)  评论(0编辑  收藏  举报