入栈/出栈

栈的push/pop操作

#include<iostream>
#include<vector>
using namespace std;
struct node
{
    int data;
    node *next;
};
struct stack_queue
{
    node *bottom;
    node *top;
};
//入栈
stack_queue *push_stack(stack_queue *ST, int num)
{
    //stack_queue *s=new stack_queue;
    node *p=new node;
    p->data=num;
    p->next=NULL;
    if(ST->bottom==NULL)
    {
        ST->bottom=p;
        ST->top=p;
    }
    else
    {
        ST->top->next=p;
        ST->top=p;
    }
    return ST;
}
//出栈
stack_queue *pop_stack(stack_queue *ST)
{
    node *p=new node;
    node *p2=ST->bottom;
    if(ST->bottom==NULL)
    {
        cout<<"overflow"<<endl;
    }
    else
    {
        p=ST->top;
        if(ST->bottom==ST->top)
        {
            ST->bottom=NULL;
            ST->top=NULL;
            delete p;
        }
        else
        {
            while(p2->next!=ST->top) p2=p2->next;
            p2->next=NULL;
            ST->top=p2;
            delete p;
        }
    }
    return ST;
}
//print
void print_stack(stack_queue *s)
{
    node *p=s->bottom;
    vector<int> temp;
    while(p!=NULL)
    {
        temp.push_back(p->data);
        p=p->next;
    }
    cout<<"输出栈"<<endl;
    for(int i=temp.size()-1;i>=0;i--)
        cout<<temp[i]<<endl;
}
int main()
{
    stack_queue *p=new stack_queue;
    stack_queue *p1;
    p->bottom=NULL;
    p->top=NULL;
    int x;
    char c;
    cout<<"输入要入栈的元素:"<<endl;
    while(cin>>x)
    {
        p1=push_stack(p,x);
        cin.get(c);
        if(c=='\n')
            break;
    }
    //print_stack(p1);
    stack_queue *p2=pop_stack(p1);
    print_stack(p2);
    return 0;
}

posted on 2015-06-09 20:05  Riden  阅读(229)  评论(0编辑  收藏  举报

导航