码迷,mamicode.com
首页 > 其他好文 > 详细

栈--数组实现

时间:2014-07-07 19:58:11      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   os   

 

用数组实现栈避免了使用指针,但是存在的缺陷是必须提前确定数组的大小,一般来说,这并不是太大的问题。:

数组实现栈:

           首先定义一个结构,TopOfStack表示栈顶,当TopOfStack为-1时,表示空栈。数组array用于存放栈元素

           进栈(push)时  ++TopOfStack 然后把元素加进数组。出栈(pop)时直接 TopOfStack--;

c语言实现:

#ifndef _stack_h

struct stack;
typedef struct stack *Stack;
typedef int ElementType;

int isEmpty(Stack s);
int isFull(Stack s);
Stack CreateStack(int MaxElements);
void Push(ElementType x,Stack s);
ElementType Top(Stack s);
void Pop(Stack s);
ElementType TopAndPop(Stack s);
#endif
#include<stdio.h>
#include<stdlib.h>
#include"stack_array.h"

#define ElementTOS (-1)
#define MinStackSize (5)

struct stack{
    int Capacity;
    int TopOfStack;
    ElementType *Array;
};

int isEmpty(Stack s)
{
    return s->TopOfStack == ElementTOS;
}
int isFull(Stack s)
{
    return s->TopOfStack == s->Capacity;
}
Stack CreateStack(int MaxElements)
{
    Stack s;
    if(MaxElements<MinStackSize)
    {
        printf("The stack is too small!\n");
        return NULL;
    }
    s = (Stack)malloc(sizeof(struct stack));
    if(s==NULL)
    {
        printf("out of space!\n");
        return NULL;
    }
    s->Capacity = MaxElements-1;
    s->TopOfStack = ElementTOS;
    s->Array = (ElementType *)malloc(MaxElements*sizeof(ElementType));
    return s;
}
void Push(ElementType x,Stack s)
{
    if(!isFull(s))
        s->Array[++s->TopOfStack] = x;
    else 
        printf("The stack is Full!\n");
}
ElementType Top(Stack s)
{
    if(!isEmpty(s))
        return s->Array[s->TopOfStack];
    else
    {
        printf("The stack is Empty!\n");
        return 0;
    }
}
void Pop(Stack s)
{
    if(!isEmpty(s))
        s->Array[s->TopOfStack--];
    else 
        printf("The stack is Empty!\n");
}
ElementType TopAndPop(Stack s)
{
    if(!isEmpty(s))
        return s->Array[s->TopOfStack--];
    else
    {
        printf("The stack is empty!\n");
        return 0;
    }
}
int main()
{
    Stack s;
    s = CreateStack(6);
    Push(1,s);
    Push(2,s);
    Push(3,s);
    Push(4,s);
    Push(5,s);
    Push(6,s);
    Push(7,s);
    
    for(int i=0;i<6;i++)
    {
        printf("The top of stack is %d\n",Top(s));
        Pop(s);
    }
    Pop(s);
    return 0;
}

 bubuko.com,布布扣

栈--数组实现,布布扣,bubuko.com

栈--数组实现

标签:style   blog   http   color   使用   os   

原文地址:http://www.cnblogs.com/avengervirus/p/3813272.html

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