链栈的操作

来源:互联网 发布:爱奇艺网络电影排行榜 编辑:程序博客网 时间:2024/06/11 16:42
//链栈的基本操作#include <iostream>#include <stdio.h>#include <malloc.h>typedef struct node{    int data;    struct node *next;}node,*linkstack;//初始化栈void init(linkstack *top){    *top=NULL;}//入栈void push(linkstack *top,int x){    linkstack s = (linkstack)malloc(sizeof(node));    s->data=x;    s->next=*top;    *top=s;    printf("%d 入栈成功!\n",x);}//出栈void pop(linkstack *top){    linkstack s = (linkstack)malloc(sizeof(node));    int e=0;    if(NULL==s)        printf("分配失败");    else{        s = *top;        e=s->data;        *top=s->next;        printf("出栈的元素是:%d ",e);    }    s=NULL;}//取栈顶元素int gettop(linkstack top){    if(top!=NULL)        return top->data;    else        printf("栈空!不存在栈顶元素!\n");    return 0;}//打印栈内元素void display(linkstack s){    while(s!=NULL){        printf("%d ",s->data);        s=s->next;    }}int main(){    linkstack s;    init(&s);    push(&s,2);    push(&s,3);    display(s);    printf("\n");    pop(&s);    printf("\n");    push1(&s,4);    printf("\n");    int x = gettop(s);    printf("栈顶元素是:%d",x);    return 0;

这里写图片描述

原创粉丝点击