- #include <stdio.h>
- #include <stdlib.h>
- typedef int elem;
- //定义基本栈
- struct stack{
- elem data;
- struct stack *next;
- };
- //定义指向栈的指针
- typedef struct stack node;
- typedef node *pstack;
- pstack push(pstack top,elem e)
- {
- pstack p;
- p = (pstack)malloc(sizeof(node));
- if(!p){
- printf("分配失败");
- exit(-1);
- }
- p->data = e;
- p->next = top;
- top = p;
- return top;
- }
- pstack pop(pstack top)
- {
- pstack p;
- elem e;
- e = 0;
- p = top;
- if(!top){
- exit(-1);
- }
- e = p->data;
- top = p->next;
- free(p);
- return top;
- }
- void print_stack(pstack top)
- {
- pstack p;
- p = top;
- while(p){
- printf("s:%d\\t",p->data);
- p = p->next;
- }
- printf("\\n");
- }
- int main()
- {
- pstack s;
- int i;
- s = (pstack)malloc(sizeof(node));
- if(!s){
- printf("分配失败");
- exit(-1);
- }
- s->next = NULL;
- for(i=0;i<10;i++)
- {
- s = push(s,i);
- }
- print_stack(s);
- s = pop(s);
- print_stack(s);
- return 1;
- }
- //该片段来自于http://www.codesnippet.cn/detail/2110201410736.html
来源: http://www.codesnippet.cn/detail/2110201410736.html