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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值