毕业编程总结2——栈/队列

啊我终于要开始coding了,作为小菜鸡自然不能跟ACM大神们卷互联网大厂,那么我就乖乖的飞回我的小青岛跟小哥哥幸福快乐的生活叭哈哈哈~~

银行国企等科技岗对编程要求比较基础,因此本博客将总结基础类型编程题目~

二、栈/队列

栈以及队列均属于线性结构,线性结构指的是逻辑结构,存储结构指在内存中的存储方式。线性表有顺序存储以及链式存储两种方式,两者各有优劣。顺序存储可以实现随机存取O(1),但在插入删除时需要移动大量元素O(n),并且顺序存储需要连续的存储空间,容易造成碎片;链式存储中每个元素的存储不一定是连续的,可以高效利用存储空间,实现高效插入、删除,但需要顺序存取。

栈是只能在一端进行插入删除的线性表,其应用很多:递归调用、进制转换、括号匹配、四则运算、行编辑程序(将输入缓冲区设置为栈结构)等等。

利用STL非常方便,stack

  • top():返回一个栈顶元素的引用,类型为 T&。如果栈为空,返回值未定义。
  • push(const T& obj):可以将对象副本压入栈顶。这是通过调用底层容器的 push_back() 函数完成的。
  • push(T&& obj):以移动对象的方式将对象压入栈顶。这是通过调用底层容器的有右值引用参数的 push_back() 函数完成的。
  • pop():弹出栈顶元素。
  • size():返回栈中元素的个数。
  • empty():在栈中没有元素的情况下返回 true。

例1:遍历链表,首先知道链表的构建以及遍历输出

#include<iostream>
#include<algorithm>
using namespace std;
struct node{
    int x;
    node* next;
};

node* create(int a[],int n)  //带头结点的链表构造
{
    node* head,*p,*pre;
    head = new node;
    head->next = NULL;
    pre = head;
    for(int i=0;i<n;i++)
    {
        p = new node;
        p->x = a[i];
        p->next = NULL;
        pre->next = p;
        pre = p;
    }
    return head;
}

int main()
{
    int n,a[1010];
    while(cin>>n)
    {
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        sort(a,a+n);  //在头文件algorithm中的sort函数,可以与cmp函数一起使用自定义排序方式
        node* L = create(a,n);
        
        L = L->next;
        int flag = 1;
        while(L){
            if(flag)
            {
                cout<<L->x;
                flag = 0;
                L=L->next;
            }
            else
            {
                cout<<' '<<L->x; //利用指向节点的指针输出值
                L=L->next;
            }
                
             
        }
        cout<<endl;
        
    }
}

例2:栈操作练习

#include<iostream>
#include<stack>
using namespace std;
stack<int>s;
int main()
{
    int n;
    char a;
    while(cin>>n)
    {
        for(int i=0;i<n;i++)
        {
           cin>>a;
            if(a=='A')
            {
                if(s.empty())
                {
                    cout<<"E"<<endl;
                }
                else{
                    cout<<s.top()<<endl;
                }
            }
            if(a=='P')
            {
                int num;
                cin>>num;
                s.push(num);
                
            }
            if(a=='O')
            {
                if(!s.empty())
                    s.pop();
                
            }
        }
    }
    cout<<endl;
}

例3. 计算器的实现应用栈(不加括号的) 

在此问题中字符之间存在空格,读入带有空格的字符串,可以用getline(s),在字符串的结尾会存‘0’以表示字符串结束。cin>>s,读入一个字符串不含空白符。

#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
stack<char>op;
stack<double>in;
string s;

int mat[][5]={  //优先级矩阵,0=‘#’,1=‘+’,2=‘-’,3=‘*’,4=‘/’
    1,0,0,0,0,
    1,0,0,0,0,
    1,0,0,0,0,    mat[i][j]=1,表示符号i的优先级高于符号j
    1,1,1,0,0,
    1,1,1,0,0,
};
//如果是运算符,则retop = true, retnum中为运算符编号
//如果是运算数,则retop = false, retnum中为具体什么运算数
void get(bool &retop, int &retnum, int &i) //在主调函数中还需要操作这些变量,因此传引用参数(地址值) 
{
    if(s[i]>='0'&&s[i]<='9')
    {
        retop = false;
        double temp = s[i]-'0';
        for(i++;s[i]>='0'&&s[i]<='9';i++) //将字符形式的数字拆解成数字
        {
            temp = temp*10+(s[i]-'0');
        }
        retnum=temp;
        i++;
    }
    else{
        retop = true; //说明是运算符
        if(s[i]=='#')
            retnum = 0;
        else if(s[i]=='+')
            retnum = 1;
        else if(s[i]=='-')
            retnum = 2;
        else if(s[i]=='*')
            retnum = 3;
        else if(s[i]=='/')
            retnum = 4;
        i += 2 ; // 跳过空格以及本字符
        
    }
    
}
int main(){
    while(getline(cin,s)) //cin不能获取空格,使用getline能直接获取一行,空格也保留的
    {
        bool retop; // 返回当前字符是不是运算符,是的话为true,否则为false;
        int retnum; // 返回当前字符是不是数字
        int i=0;
        s = "# "+ s +" #"; //在C++中字符串可以使用加号进行拼接,已经重载了
        while(!op.empty())op.pop(); //清空栈
        while(!in.empty())in.pop();
        while(true)
        {
            get(retop,retnum,i);
            if(retop==false)
            {
                in.push((double)retnum);
            }
            else{
                double result;
                if(op.empty()||mat[retnum][op.top()]==1)
                {
                    op.push(retnum);
                }
                else{
                    while(mat[retnum][op.top()]==0)
                    {
                        double a = in.top(); //一定要注意左右操作数的问题,先出来的为右操作数,后出栈的是左操作数
                        in.pop();
                        double b = in.top();
                        in.pop();
                        int c = op.top();
                        op.pop();
                        if(c==1)
                            result = a+b;
                        if(c==2)
                            result = b-a;
                        if(c==3)
                            result = a*b;
                        if(c==4)
                            result = b/a;
                        in.push(result);
                        
                    }
                    op.push(retnum);
                }
            }
            if(op.size()==2&&op.top()==0)
                break;
        }
        printf("%.2lf\n",in.top());
    }
    return 0;
}

描述

输入一个表达式(用字符串表示),求这个表达式的值。

保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。

输入描述:

输入一个算术表达式

输出描述:

得到计算结果

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

bool cmp_op_priority(char a,char b)
{
    if((a=='*'||a=='/')&&(b=='+'||b=='-'))return true;
    if((a=='+'||a=='-')&&(b=='+'||b=='-'))return true;
    return false;
}
vector<string>to(string &pre)
{
    stack<char>op;
    vector<string>v;
    string temp;
    for (int i=0;i<pre.size();i++)
    {
        if (pre[i]=='['||pre[i]=='{')
            pre[i]='(';
        if (pre[i]==']'||pre[i]=='}')
            pre[i]=')';
    }
    for (int i=0;i<pre.size();i++)
    {
        if ((i==0&&pre[i]=='-')||(i>0&&pre[i]=='-'&&pre[i-1]=='('))
        {
            pre.insert(i, "0");
        }
    }
    for(int i = 0;i<pre.size();i++)
    {
       
        if(pre[i]>='0'&&pre[i]<='9') //遇到数字将数字直接压栈
        {
            temp = pre[i++];
            while(pre[i]>='0'&&pre[i]<='9')
            {
                temp+=pre[i];
                i++;
            }
            i--;
            v.push_back(temp);
        }
        else           
        {
            if(op.empty()&&pre[i]=='(')    //左括号直接压栈
            { 
                op.push(pre[i]);
            }
            else if(pre[i]==')')           //右括号进行数值计算,遇到左括号结束,最终将(弹出
            {
                while(op.top()!='(')
                {
                    temp = op.top();
                    v.push_back(temp);
                    op.pop();
                }
                op.pop();
            }
            else{
                 while((!op.empty()&&cmp_op_priority(op.top(), pre[i]))) 
                {
                    //temp="";
                    temp=op.top();          //栈顶优先级大,栈顶运算符出栈
                    v.push_back(temp);
                    op.pop();
                }
                op.push(pre[i]);
            }
        }
    }
    while(!op.empty()){
        temp=op.top();
        v.push_back(temp);
        op.pop();
    }
    return v;
}

int cal(vector<string> v)
{
    stack<int>num;
    for(int i = 0;i<v.size();i++)
    {
        if(v[i][0]>='0'&&v[i][0]<='9') //说明为数字
        {
            int nm = atoi(v[i].c_str());    //将C++中的string类型转化为C中的字符串Char*
            num.push(nm);                   //aoti() C中的函数,能够将字符串转化为整数
        } 
        else                               //aotf() 转化为浮点数
        {
            int B=num.top();
            num.pop();
            int A=num.top();
            num.pop();
            if (v[i]=="+")
                num.push(A+B);
            if (v[i]=="-")
                num.push(A-B);
            if (v[i]=="*")
                num.push(A*B);
            if (v[i]=="/")
                num.push(A/B);
        }
    }
    return num.top();
}

int main()
{
    string str;
    vector<string>v;
    while(cin>>str)
    {
        v = to(str);
        cout<<cal(v)<<endl;
    }
}
该题非常标准的将中缀表达式转化为后缀表达式,进而求解。

例4:括号匹配

读入序列,从左向右遍历序列,遇到左括号则压栈,遇到右括号则判断此时栈是否为空,若为空则匹配失败,否则取栈顶元素,若栈顶元素为左括号则成功匹配一堆;党遍历完成序列以后,栈仍有括号存在则说明匹配失败。                                                                                                                                                                                                                                                                                                                                                                                                                                 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值