public class SeqStack { int data[]; int MAX=100; int size;code
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(); }
}element
c語言it
#include<stdio.h>io
#include<stdlib.h>class
#define max_size 100static
typedef int elementType;top
typedef struct seq_stack{語言
int top;di
elementType data[max_size];co
} 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;
}