用数组实现栈避免了使用指针,但是存在的缺陷是必须提前确定数组的大小,一般来说,这并不是太大的问题。:
数组实现栈:
首先定义一个结构,TopOfStack表示栈顶,当TopOfStack为-1时,表示空栈。数组array用于存放栈元素
进栈(push)时 ++TopOfStack 然后把元素加进数组。出栈(pop)时直接 TopOfStack--;
c语言实现:
#ifndef _stack_h struct 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; }
栈--数组实现
时间: 2024-12-27 21:02:47