栈-基本操作(C版)

来源:互联网 发布:域名侵犯商标权的案例 编辑:程序博客网 时间:2024/05/17 20:26

栈(Stack) 是限制插入和删除只能在一个位置上进行的表,该位置是表额末端,叫栈的顶部(top)。

一般常有的操作有

/**判断堆栈是否为空栈**/int isEmpty(Stack s)/**判断堆栈是否已满**/int isFull(Stack s)/**入栈**/void push(Stack s,int item)/**出栈**/int pop(Stack s)/**取栈顶元素**/int top(Stack s)

Stack.c

#include <stdio.h>#include <stdlib.h>#define EMPTYTOP -1;/**定义一个堆栈**/typedef struct StackRec{int size;//栈大小int top;//栈指针int *Array;}LStack,*Stack;/**栈指针指向栈底**/void makeEmpty(Stack s){s->top = EMPTYTOP;}/**创建一个大小为size 的空栈**/Stack createStack(int size){Stack stack;stack = (Stack)malloc(sizeof(LStack));if(stack==NULL){printf("error!");return NULL;}stack->Array = malloc(sizeof(int)*size);if(stack->Array==NULL){printf("error!");return NULL;}stack->size = size;makeEmpty(stack);return stack;}/**判断堆栈是否为空栈**/int isEmpty(Stack s){return s->top == EMPTYTOP;}/**判断堆栈是否已满**/int isFull(Stack s){return s->top == s->size;}/**入栈**/void push(Stack s,int item){if(isFull(s)){printf("the full Stack");} else {s->Array[++s->top] = item;}}/**出栈**/int pop(Stack s){if(isEmpty(s)){printf("the Empty Stack");} else {return s->Array[s->top--];}return -1;}/**取栈顶元素**/int top(Stack s){if(!isEmpty(s)){return s->Array[s->top];}return -1;}/**释放空间**/void disPoseStack(Stack s){if(s!=NULL){free(s->Array);free(s);}}int main(void){int capacity = 10;Stack s = createStack(capacity);push(s,1);push(s,2);push(s,3);printf("%d\n",top(s));int x = pop(s);printf("%d\n",x);printf("%d\n",top(s));disPoseStack(s);return -1;}



原创粉丝点击