Data Structure learning——-Stack

1 list&array:The size of list is variable while array contains constant number of elements.

2Stack:

Stack is a version of list that is particularly useful is reversing the order of the list.

last in,first out is the basic property of stack.An example is plates or trays on a spring-loaded device so that only the top item is moved when it is added or deleted.

push means adds an item to a stack.pop means we remove an item from a stack.

c++ standard library enable following operations:

1.create the stack,leave it empty.

like stack<int>num;

2Test whether the stack is empty.return boolean values.

num.empty();

3Push an item onto the top of the stack,provided the stack is not empty.

num.push(item);

4 Pop the entry off the top of the stack,provided the stack is not empty.

num.pop();

5Retrieve the Top entry of the stack,provided that the stack is not empty.

cout<<num.top();

 

Code1:Reversing the order of a list

#include<iostream>
#include<stack>
using namespace std;
int main()
{
    int item;
    stack<int>num;//means that declare and intialize a stack,the name of stack is "num" and element of it is int type
    cout<<"reversing the stack"<<endl;
    for(int i=0;i<5;i++)
    {
        cin>>item;
        num.push(item);
    }
    while(!num.empty())
    {
        cout<<num.top()<<' ';//top is the last one to come in ,like loaded plates
        num.pop();
    }
    cout<<endl;
    return 0;
}

 

Code2:bracket mismatch

/* The program has notified the user of any bracket mismatch in the standard input file
* class stack is needed
*/
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
stack <char> opening;

char symbol;
bool is_matched=true;
while(true )
{
    if(!is_matched)
        break;
    cin.get(symbol);
    if(symbol=='\n')break;
    if(symbol=='{'||symbol=='('||symbol=='[')
        opening.push(symbol);
if(symbol=='}'||symbol==')'||symbol==']')
    {
    if(opening.empty())//if stack is empty
    {
        cout<<"Unmatched closing bracket"<<symbol<<"bracket"<<endl;
        is_matched=false;
    }
    else
    {
        char match;
        match=opening.top();
        opening.pop();
        is_matched=(symbol=='}'&&match=='{'||symbol==')'&&match=='('||symbol==']'&&match=='[');
        if(!is_matched)
            cout<<"Bad matched"<<match<<symbol<<endl;
    }
    }
}
if(!opening.empty())
    cout<<"Unmatched opening bracket detected"<<endl;
return 0;
}

原文链接: https://www.cnblogs.com/pkusirius/archive/2010/04/04/1704372.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Data Structure learning-------Stack

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/9530

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月6日 下午10:23
下一篇 2023年2月6日 下午10:23

相关推荐