java、C语言实现数组模拟栈

java:

public class ArrayStack {

    private int[] data;
    private int top;
    private int size;

    public ArrayStack(int size) {
        this.data = new int[size];
        this.size = size;
        this.top = -1;
    }

    public boolean isEmpty() {
        if (this.top == -1) {
            return true;
        }
        return false;
    }

    public boolean push(int x) {
        if (this.top == this.size - 1) {
            return false;
        } else {
            this.top++;
            this.data[top] = x;
            return true;
        }
    }

    public int pop() {
        if (isEmpty()) {
            return -1;
        }
        return data[top--];
    }
}

c语言:

#include <stdio.h>
#include <stdlib.h>
#define MAX 10
typedef struct Stack
{
    int data[MAX];
    int top;
}Stack;

void initStack(Stack *stack)
{
    stack->top=-1;
}

int isEmpty(Stack stack)
{
    if(stack.top==-1)
    {
        return 1;
    }
    return 0;
}

int push(Stack *stack,int x)
{
    if(stack->top==MAX-1)
    {
        return 0;
    }
    else
    {
        stack->top++;
        stack->data[stack->top]=x;
        return 1;
    }
}

int pop(Stack *stack,int *x)
{
    if(isEmpty(*stack))
    {
        return 0;
    }
    else
    {
        *x=stack->data[stack->top];
        stack->top--;
        return 1;
    }
}

int main()
{
    Stack *stack=(Stack*)malloc(sizeof(Stack));
    initStack(stack);
    push(stack,1);
    push(stack,2);
    push(stack,3);
    push(stack,4);
    int x,y;
    pop(stack,&x);
    pop(stack,&y);
    printf("%d,%d
",x,y);
    return 0;
}

原理一样,但是用java写会感觉更舒服,用面向对象的思想比较清楚。