入栈出栈代码实现

了解更多栈的知识,请点击 

#include<stdio.h>
#include<iostream>
typedef struct node{
 int date;
 node * next;
}SeqStack ;
SeqStack * init_SeqStack(SeqStack * top){
 top=NULL;
 return top;
}
int is_Empty(SeqStack * top){
 if(top==NULL)return 1;
 else return 0;
}
SeqStack * push_Stack(SeqStack * top){
  SeqStack * New;
  New=(SeqStack *)malloc(sizeof(SeqStack));
  printf("请输入要入栈的元素\n");
  scanf("%d",&New->date);
  New->next=top;
  top=New;
  return top;
}
SeqStack * pop_Stack(SeqStack * top,int &m){
 SeqStack * p=NULL;
 if(!is_Empty(top)){ 
  m=top->date;
  p=top;
  top=top->next;
  free(p);
  return top; 
 }
}
SeqStack * top_Stack(SeqStack * top,int &m){
 if(!is_Empty(top)){
  m= top->date;
  return top;
 }
}
int main(){
 int m=0;
 SeqStack * s=NULL;
 init_SeqStack(s);
 s=push_Stack(s);
 s=push_Stack(s);
 s=push_Stack(s);
 s=push_Stack(s);
 s=top_Stack(s,m);
 printf("%d\n",m);
 s=top_Stack(s,m);
 printf("%d\n",m);
 s=pop_Stack(s,m);
 printf("%d\n",m);
 s=top_Stack(s,m);
 printf("%d\n",m);
 if(is_Empty(s)) printf("栈现在是空了");
 system("pause");
 return 0;
}

////////////////////////////////////////////

//顺序栈的初始化,建立,插入,查找,删除。  //

//Author:Wang Yong                 //   

//Date: 2010.8.19                  //

////////////////////////////////////////////

#include <stdio.h>

#include <stdlib.h>

#define  MAX 100                //定义最大栈容量

typedef int ElemType;

///////////////////////////////////////////

//定义栈类型

typedef struct

{

    ElemType data[MAX];

    int top;

}SeqStack;

///////////////////////////////////////////

//栈的初始化

SeqStack SeqStackInit()

{

    SeqStack s;

    s.top = -1;

    return s;

}

///////////////////////////////////////////

//判断栈空的算法

int SeqStackIsEmpty(SeqStack s)

{

    if(s.top == -1)

        return 0;

    else

        return 1;

}

///////////////////////////////////////////

//进栈的算法

void SeqStackPush(SeqStack &s,ElemType x)

{

    if(s.top == MAX-1)              //进栈的时候必须判断是否栈满

        printf("stack full\n");

    s.top++;

    s.data[s.top] = x;

}

//////////////////////////////////////////

//出栈的算法

ElemType SeqStackPop(SeqStack &s)

{

    if(s.top == -1)             //出栈的时候必须判断是否栈空

        printf("stack empty\n");

    ElemType x;

    x = s.data[s.top];

    s.top--;

    return x;

}

//////////////////////////////////////

int main()

{

    SeqStack  stack;

    stack = SeqStackInit();

    printf("请输入进栈的元素:");

    ElemType x;

    while(scanf("%d",&x) != -1)

    {

        SeqStackPush(stack,x); 

    }

    printf("出栈的结果:");

    while(stack.top != -1)

    {

        printf("%d ",SeqStackPop(stack));

    }

    printf("\n");

    return 0;

}

猜你喜欢

转载自blog.csdn.net/hou_shiyu/article/details/81204601