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;
}

posted on 2010-04-04 21:58  梦涵  阅读(310)  评论(0编辑  收藏  举报