栈stack - 是限定在表尾进行插入或删除的线性表
#ifndef __STACK_H__ #define __STACK_H__ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLF -1 #define OVERFLOW -2 #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int Status; typedef int SElemType; typedef struct { SElemType *base; SElemType *top; int stacksize; int length; }SqStack; #endif
#include"stack.h" #include<stdlib.h> #include<stdio.h> Status InitStack(SqStack &S) { S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType)); if(!S.base) { exit(OVERFLOW); } S.top = S.base; S.stacksize = STACK_INIT_SIZE; S.length = 0; return OK; } Status GetTop(SqStack S, SElemType &e) { if(S.top == S.base) { return ERROR; } e = *(S.top - 1); return OK; } Status Push(SqStack &S, SElemType e) { if(S.top - S.base >= S.stacksize) { S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType)); if(!S.base) { exit(OVERFLOW); } S.top = S.base + S.stacksize; S.stacksize += STACKINCREMENT; } *S.top++ = e; S.length++; return OK; } void show(SqStack &S) { printf("stacksize = %d ", S.stacksize); printf("length = %d ", S.length); if(S.length == 0) { return; } for(int i = 0; i < S.length; i++) { printf("index = %d, value = %d ", i, S.base[i]); } } Status Pop(SqStack &S, SElemType &e) { if(S.top == S.base) { return ERROR; } e = *--S.top; S.length--; return OK; } Status StackEmpty(SqStack &S) { return S.length == 0; } void conversionTo8(int tenNumber){ SqStack S; InitStack(S); int n; printf("%d to eight number ", tenNumber); while(tenNumber) { Push(S, tenNumber % 8); tenNumber = tenNumber / 8; } while(!StackEmpty(S)){ Pop(S, n); printf("%d", n); } printf(" "); } int main() { SElemType e; SqStack S; InitStack(S); Push(S, 1); Push(S, 2); show(S); Pop(S, e); show(S); int i = StackEmpty(S); printf("i = %d ", i); conversionTo8(1348); return OK; }