棧--數組實現

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   os   

 

用數組實現棧避免了使用指標,但是存在的缺陷是必須提前確定數組的大小,一般來說,這並不是太大的問題。:

數組實現棧:

           首先定義一個結構,TopOfStack表示棧頂,當TopOfStack為-1時,表示空棧。數組array用於存放棧元素

           進棧(push)時  ++TopOfStack 然後把元素加進數組。出棧(pop)時直接 TopOfStack--;

c語言實現:

#ifndef _stack_hstruct 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;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.