基於 Linux 的順序棧程式碼
阿新 • • 發佈:2019-01-07
/************************************************************************* > File Name: sqstack.c > Author: Wenfei6316 > Mail: [email protected] > Created Time: 2018年06月17日 星期日 22時13分21秒 ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string.h> #include <time.h> #define MAXSIZE 25 typedef int data_t; typedef struct { data_t data[MAXSIZE]; int top; }SqNode, *SqStack; SqStack CreateEmptyStack(void); void PushStack(SqStack stack, data_t value); void PopStack(SqStack stack, data_t *value); int EmptyStack(SqStack stack); int FullStack(SqStack stack); int main(int argc, const char *argv[]) { data_t data; SqStack stack; stack = CreateEmptyStack(); PushStack(stack, 20); PushStack(stack, 30); PopStack(stack, &data); printf("Pop: %d\n", data); PopStack(stack, &data); printf("Pop: %d\n", data); PopStack(stack, &data); printf("Pop: %d\n", data); if (!EmptyStack(stack)) printf("Stack is empty!\n"); if (!FullStack(stack)) printf("Stack is full!\n"); free(stack); return 0; } //建立空順序棧 SqStack CreateEmptyStack(void) { SqStack stack; stack = (SqStack)malloc(sizeof(SqNode)); if (stack == NULL) { perror("Create sequence stack failed!\n"); exit(EXIT_FAILURE); } stack->top = -1; return stack; } //壓棧 void PushStack(SqStack stack, data_t value) { if (stack->top == MAXSIZE-1) { printf("Stack is full!\n"); return ; } stack->top++; stack->data[stack->top] = value; return ; } //彈棧 void PopStack(SqStack stack, data_t *value) { *value = 0; if (stack->top == -1) { printf("Stack is empty!\n"); return ; } *value = stack->data[stack->top]; stack->top--; return ; } //空棧判斷 int EmptyStack(SqStack stack) { return stack->top == -1 ? 0 : 1; } //滿棧判斷 int FullStack(SqStack stack) { return stack->top == MAXSIZE-1 ? 0 : 1; }