数据结构-栈

本文深入讲解了栈数据结构的手写实现及C++ STL的应用,并通过两个实例演示如何使用栈来解决实际问题,如检查括号匹配性和判断合法的出栈序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(stack)是一种先进后出的基本数据结构


一、实现



(一)手写

需要一个栈顶指针(指向空位置),数组作栈

(在结构体内写更好)

#include <iostream>
using namespace std;

#define EMPTY -9999999

int stack[1001];
int top = 1;
int n, tmp;

void push(const int x) { 
	stack[top ++] = x;
}

bool empty() {
	if(top == 1) return true;
	return false;
}

int pop() {                      
	if(empty()) return EMPTY;
	return stack[-- top];
}

int Func_top() {                    
	return stack[top-1];         
}

int main() {
	cin >> n;
	for(int i=0; i<n; i++) {
		cin >> tmp;
		push(tmp);
	}
	while(!empty()) {
		cout << Func_top() << " ";
		pop();
	}
	return 0;
}



(二)C++ STL


stack<int> a;

常用操作:

a. push(x) 将x入栈

a. top() 访问栈顶元素

a. pop() 弹出(不返回)栈顶元素

a. empty() 判断栈是否为空

a.size() 返回栈中元素个数


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

stack<int> a;
int n, tmp;

int main() {
	cin >> n;
	for(int i=0; i<n; i++) {
		cin >> tmp;
		a.push(tmp);
	}
	while(!a.empty()) {
		cout << a.top() << " ";
		a.pop();
	}
	return 0;
}


二、应用

判断括号是否合法。‘('入栈,')'出栈即可

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

char a[10001];
int n;

bool Judge(char *c) {
    int pos = 0;
    stack<int> S;
    while(c[pos] != '@') {
        if(c[pos] == '(') S.push(c[pos]);
        else if(c[pos] == ')') {
            if(!S.empty() && S.top() == '(') S.pop(); 
            else return false;
        }
        pos ++;
    }
    if(S.empty()) return true;
    return false;
}

int main() {
    cin >> a;
    if(Judge(a)) cout << "YES" << endl;
    else cout << "NO" << endl;
    return 0;
}


判断合法出栈序列。(入栈序列1,2,3,..., n)

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
//判断合法出栈序列
int n, w;
int s[1001];
stack<int> S;

int main() {
    cin >> n;
    for(int i=1; i<=n; i++) cin >> s[i];
    w = 1;
    for(int i=1; i<=n; i++) {
        while(S.empty() || S.top() != s[i]) {
            if(w > n) {
                cout << "NO" << endl;
                return 0;
            }
            S.push(w ++);
        }
        if(S.top() == s[i]) S.pop();
    }
    if(S.empty()) cout << "YES" << endl;
    else cout << "NO" << endl;
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值