Stack-Array Implementation

Source: Internet
Author: User

Introduction:

Using a linked list to implement a stack has the disadvantages of "expensive to call malloc and free", especially compared with the pointer operation routine. Using arrays to implement stacks can avoid pointers. However, its disadvantage is that there may be a waste of space.


Analysis description:


The node element of the array stack.

#ifndef ERROR#define ERROR (0)#endif#ifndef OK#define OK(!ERROR)#endif#define STACK_INIT_SIZE 100#define STACKINCREMENT  10typedefint SElemType;typedef struct SqStack{SElemType*base;SElemType*top;intstacksize;}SqStack, *pStack;pStack S;

Stack initialization.

pStack InitStack(pStack S){S = (pStack)malloc(STACK_INIT_SIZE * sizeof(SElemType));if(S == NULL){return ERROR;}S->base = (SElemType *)S;S->top = S->base;S->stacksize = STACK_INIT_SIZE;return S;}

Stack operations.

pStack Push(pStack S, SElemType e){if((S->top - S->base) >= S->stacksize){S->base = (SElemType *)realloc(S, (S->stacksize + STACKINCREMENT)*sizeof(SElemType));if(S->base == NULL)return ERROR;S->top = S->base + S->stacksize;S->stacksize += STACKINCREMENT;}*S->top++ = e;return S;}

Out-of-stack operations.

SElemType Pop(pStack S){if(S->top == S->base)return 0;return *(--S->top);}

Take the top element of the stack.

SElemType GetTop(pStack S){if(S->top == S->base)return ERROR;return *(S->top - 1);}

Evaluate the stack length.

int GetLength(pStack S){int length = 0;if(S->top == S->base)return 0;        pStack Tmp = S;while(Tmp->top-- != Tmp->base)length++;return length;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.