public class SeqStack { int data[]; int MAX=100; int size;
public SeqStack(){
size=-1;
data=new int [100];
}
public void push(int i)throws Exception{
if(size==MAX-1)
throw new Exception("栈已经满了");
size++;
data[size]=i;
System.out.println(data[size]);
}
public void pop()throws Exception{
if(size==-1)
throw new Exception("栈已经空了");
System.out.println(data[size]);
size--;
}
public static void main(String[] args) throws Exception{
SeqStack s= new SeqStack();
for(int i=0;i<10;i++)
s.push(i+1);
for(int i=0;i<11;i++)
s.pop();
}
}
c语言
#include<stdio.h>
#include<stdlib.h>
#define max_size 100
typedef int elementType;
typedef struct seq_stack{
int top;
elementType data[max_size];
} Stack;
Stack s;
void init(Stack *stack){
stack->top=-1;
}
//进栈
void push(Stack *st,elementType x){
if(st->top==max_size-1){
return;
}
st->top++;
st->data[st->top]=x;
printf("%d\n",st->data[st->top]);
} //出栈
void pop(Stack *st,int *x){
if(st->top ==-1){
printf("stack is null");
return;
}
*x=st->data[st->top];
st->top--;
}
int main(){
init(&s);
for(int i=0;i<5;i++)
push(&s,i+1);
int x;
for(int i=0;i<5;i++){
pop(&s,&x);
printf("%d\n",x);
}
return 0;
}