用数组实现线性栈

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;

}

转载于:https://my.oschina.net/u/2511906/blog/3085938

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值