码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-07-11 22:49:57      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   io   div   

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\n",x,y);
    return 0;
}

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

java、C语言实现数组模拟栈,布布扣,bubuko.com

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

标签:style   blog   java   color   io   div   

原文地址:http://www.cnblogs.com/nannanITeye/p/3833072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!