有两种有意思的线性表,它们分别是栈(stack)和队列(queue)。
栈是这样规定的,它的元素遵守先进后出的原则,且出入口只有一个,叫做栈顶。进栈的动作叫做push,出栈的动作叫做pop。
因为它基于线性表,又有这么简单清晰的定义,所以实现上还是比较容易的。
//2013.3.6 //lincoln //stack sequence storage structure #include <stdio.h> #define OK 1 #define ERROR -1 #define TRUE 1 #define FALSE 0 #define MAXLENGTH 20 struct Stack { int data[MAXLENGTH]; int top; }; int push(struct Stack *stack,int element) { if(stack->top == MAXLENGTH-1) return ERROR; int index = ++stack->top;//top先自增再赋值给index //int index = stack->top++;//top先赋值给index再自增。这点请注意。 stack->data[index] = element; return OK; } int pop(struct Stack *stack) { if(stack->top == -1) return ERROR; stack->top--; return OK; } void print(struct Stack *stack) { if(stack->top == -1) return ; int size = stack->top+1; for(int i =0;i<size;++i) { printf("stack->data[%d]=%d\n",i,stack->data[i]); } } int main() { struct Stack stack = { {0}, 0 }; push(&stack,30); push(&stack,12); print(&stack); pop(&stack); print(&stack); return 0; }