您的位置:首页 > 其它

链栈基本操作

2012-08-22 09:25 204 查看
链栈的操作:

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

struct node
{
    int val;
    node *next;
};

node *push(node *top,int x)
{
    node *p = new node();
    p->val = x;
    p->next = top;
    top = p;
    return top;
}

node *pop(node *top,int *x)
{
    if(top == NULL)
        return NULL;
    node *q = top;
    *x = top->val;
    top = top->next;
    delete q;
    return top;
}

void print(node *top)
{
    node *p = top;
    if(p == NULL) return;
    while(p != NULL)
    {
        printf("%d ",p->val);
        p = p->next;
    }
    cout<<endl;
}

int main()
{
    int n,x;
    node *top = NULL;
    while(cin>>n)
    {
        while(n--)
        {
            cin>>x;
            top = push(top,x);
        }
        print(top);
        top = pop(top,&x);
        cout<<x<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: