用数组实现一个栈
#include<stdio.h>
#define STACK_SIZE 64 /*棧大小*/
#define TOP_OF_STACK -1 /*棧頂位置*/
typedef int ElementType; /*棧元素類型*/
#define SUCCESS 0
#define FAILURE -1
/*定義棧結構*/
typedef struct StackInfo
{int topOfStack; /*記錄棧頂位置*/ElementType stack[STACK_SIZE]; /*棧數組,也可以使用動態數組實現*/
}StackInfo_st;
/*函數聲明*/
int stack_push(StackInfo_st *s,ElementType value);
int stack_pop(StackInfo_st *s,ElementType *value);
int stack_top(StackInfo_st *s,ElementType *value);
int stack_is_full(StackInfo_st *s);
int stack_is_empty(StackInfo_st *s);
/*入棧,0表示成,非0表示出錯*/
int stack_push(StackInfo_st *s,ElementType value)
{if(stack_is_full(s))return FAILURE;/*先增加topOfStack,再賦值*/s->topOfStack++;s->stack[s->topOfStack] = value;return SUCCESS;
}
/*出棧*/
int stack_pop(StackInfo_st *s,ElementType *value)
{/*首先判斷棧是否為空*/if(stack_is_empty(s))return FAILURE;*value = s->stack[s->topOfStack];s->topOfStack--;return SUCCESS;
}
/*訪問棧頂元素*/
int stack_top(StackInfo_st *s,ElementType *value)
{/*首先判斷棧是否為空*/if(stack_is_empty(s))return FAILURE;*value = s->stack[s->topOfStack];return SUCCESS;
}
/*判斷棧是否已滿,滿返回1,未滿返回0*/
int stack_is_full(StackInfo_st *s)
{return s->topOfStack == STACK_SIZE - 1;
}
/*判斷棧是否為空,空返回1,非空返回0*/
int stack_is_empty(StackInfo_st *s)
{return s->topOfStack == - 1;
}int main(void)
{/*創建棧*/StackInfo_st stack;stack.topOfStack = TOP_OF_STACK;/*如果棧為空,則壓入元素1*/if(stack_is_empty(&stack)){printf("push value 1\n");stack_push(&stack,1);}/*訪問棧頂元素*/int topVal;stack_top(&stack, &topVal);printf("top value %d\n",topVal);/*出棧*/int popVal;stack_pop(&stack, &popVal);printf("pop value %d\n",popVal);int i = 0;while(SUCCESS == stack_push(&stack,i)){i++;}printf("stack is full,topOfStack is %d\n",stack.topOfStack);return 0;
}
總結
- 上一篇: 单精度浮点数与十六进制转换
- 下一篇: V4L2用户空间和kernel层driv