栈是一种先进后出(FILO)的数据结构。举例:我们打开一些网页,然后又关闭了几个,而当我们想要恢复之前看过的网页时,会点击恢复网页按钮,那么最先被我们关闭的网页,最后被恢复出来。
栈有两种实现方式,一种是数组实现,a[top],top指向栈顶,栈空时top为-1,每次加入元素时,top值加1,并赋值a[top]。实现简单,这里就不详细叙述了。
//入栈
int push(int* a, int top, int ele)
{
a[++top] = ele;
return top;
}
int pop(int* a, int top)
{
if(top == -1)
return -1;
printf("pop element is %d\n", a[top--]);
return top;
}
第二种是链表实现。开始栈顶head元素为空。插入一个元素后,该元素的next 节点指向head,然后将该元素置位新的head元素。 直接贴代码和运行结果。运行环境vs2010.
//链表实现栈操作
typedef struct lineStack{
int data;
lineStack *next;
}lineStack;
//入栈
lineStack * push(lineStack *stack, int data)
{
lineStack *p = (lineStack *)malloc(sizeof(lineStack));
p->data = data;
p->next = stack;
stack = p;
return stack;
}
//出栈
lineStack * pop(lineStack *stack)
{
if(stack){
printf("pop 元素:%d", stack->data);
lineStack * p = stack;
stack = stack->next;
if(stack)
{
printf("新栈顶元素 %d\n",stack->data);
}
else
puts("空栈1");
free(p);
}
else{
puts("空栈2");
}
return stack;
}
int _tmain(int argc, _TCHAR* argv[])
{
lineStack *stack = NULL;
stack = push(stack,1);
stack = push(stack,2);
stack = push(stack,3);
stack = pop(stack);
stack = pop(stack);
stack = pop(stack);
system("pause");
return 0;
}
运行截图: