The array implementation of ZJU data structure 2019 spring stack

Just started to learn the data structure and implemented a simple stack instance. It is to print the output numbers in reverse order by adjusting the...

Just started to learn the data structure and implemented a simple stack instance. It is to print the output numbers in reverse order by adjusting the top subscript.

Be careful:
1. The alias Stack is actually a pointer to struct Stack. When applying for memory to place the structure, it should be sizeof (struct Stack).
2. When the array malloc is a single element volume * number of elements
3. A simple return value can be implemented in one line.

Type name: Stack
Data object set: a finite linear table with 0 or more elements.
Operation set: stack s stack with MaxSize length, stack element item ElementType
1. Stack createstack (int MaxSize): generates an empty stack with a maximum length of MaxSize;
2. Int isfull (stack S, int maxsize): judge whether the stack S is full;
3. Void push (stack s, ElementType item): push the element item into the stack;
4. Int isempty (stack S): judge whether stack S is empty;
5. ElementType pop (stack s): delete and return the stack top element;

#include <stdio.h> #include <stdlib.h> #define ERROR -1 #define MAXSIZE 1000 typedef int ElementType; struct _stack { int* array; int top; int maxSize; }; typedef struct _stack* Stack; Stack createStack(int size); int isFull(Stack S); void Push(Stack S,int elem); int isEmpty(Stack S); int Pop(Stack S); int main(int argc, char const *argv[]) { Stack s=createStack(MAXSIZE); ElementType num; while(scanf("%d",&num)!=EOF) Push(s,num); while(!isEmpty(s)) printf("%d\n",Pop(s) ); return 0; } Stack createStack(int size) { Stack currentPtr=(Stack)malloc(sizeof(struct _stack)); currentPtr->array=(ElementType*)malloc(sizeof(ElementType)*size); currentPtr->top=-1; currentPtr->maxSize=size; return currentPtr; } int isFull(Stack S) { return (S->top==S->maxSize-1); } void Push(Stack S,ElementType elem) { if(isFull(S)) printf("The stack is full, the elem cannot join in.\n"); else S->array[++S->top]=elem; } int isEmpty(Stack S) { return (S->top==-1); } ElementType Pop(Stack S) { if(isEmpty(S)) { printf("Hollow!\n"); return ERROR; } return (S->array[(S->top)--]); }

2 December 2019, 15:37 | Views: 2110

Add new comment

For adding a comment, please log in
or create account

0 comments