链栈的基本操作

来源:互联网 发布:淘宝详情代码生成器 编辑:程序博客网 时间:2024/05/04 21:39
#include<iostream>using namespace std;struct node{    int val;    node *next;};node * push(node *top,int val){    node *p = new node();    if(p!=NULL)    {        p->val=val;        p->next=top;        top=p;    }    return top;}node *pop(node* top, int *val){    if(top==NULL)    {        return NULL;    }    node *p = top;    *val = top->val;    top = top->next;    delete p;    p=NULL;    return top; }void print(node *top){    node *p = top;    if(p==NULL)    {        return;    }    while(p!=NULL)    {        cout<<p->val<<" ";        p=p->next;    }    cout<<endl;}int main(){    int n,m,val;    node *top=NULL;    cin>>n;    while(n--)    {        cin>>m;        top=push(top,m);    }    print(top);    top=pop(top,&val);    cout<<val<<endl;    print(top);    return 0;}
0 0
原创粉丝点击