顺序栈的操作:新建一个栈,入栈,出栈
以下代码在vs2010测试通过:
/** * 栈的顺序存储 */ #include "stdafx.h" #include "stdlib.h" #include "stdio.h" #define MAXSIZE 20 typedef struct stack{ int stacks[MAXSIZE]; int top; }seqStack; void sequence_init_stack(seqStack* s){ s->top = -1; } void push_stack(seqStack* s,int value){ if(s->top < MAXSIZE-1){ s->top++; s->stacks[s->top] = value; } } int pop_stack(seqStack* s){ if(s->top == -1){ return NULL; } return s->stacks[s->top--]; } int _tmain(int argc, _TCHAR* argv[]){ seqStack s; int stackLength,em; //创建栈 sequence_init_stack(&s); //入栈 printf("请输入要入栈的数字的个数:"); scanf("%d",&stackLength); if(stackLength <= 0){ return 0 ; } for(int i=0; i < stackLength ; i++){ printf("请输入入栈的数字:"); scanf("%d",&em); push_stack(&s,em); } //出栈 printf("出栈的数字依次为:\n"); for(int j=0; j< stackLength; j++){ printf("%d\t",pop_stack(&s)); } system("pause"); return 1; }
链栈的操作:新建一个栈,入栈,出栈
#include "stdafx.h" #include "stdio.h" #include "stdlib.h" typedef struct stackNode{ int data; struct stackNode *next; }StackNodePro; typedef struct stackList{ StackNodePro* top; int count; }StackListPro; void list_stack_create(StackListPro** s){ *s = (StackListPro *)malloc(sizeof(StackListPro)); if((*s) != NULL){ (*s)->top = NULL; (*s)->count = 0 ; } } void list_stack_push(StackListPro* s,int value){ StackNodePro *snode; snode = (StackNodePro *)malloc(sizeof(StackNodePro)); if(snode != NULL){ snode->data = value; snode->next = s->top; s->top = snode; s->count++; } } int list_stack_pop(StackListPro* s){ if(s == NULL || s->count ==0){ return 0; } StackNodePro *pop_node; int pop_value; pop_value = (s->top)->data; s->count--; pop_node = s->top; s->top = s->top->next; free(pop_node); return pop_value; } int _tmain(int argc, _TCHAR* argv[]){ StackListPro *s = NULL; //建栈 list_stack_create(&s); //入栈 int push_num,push_value; printf("请输入入栈的数字个数:"); scanf("%d",&push_num); for(int i=0; i< push_num; i++){ printf("请输入入栈的数字:"); scanf("%d",&push_value); list_stack_push(s,push_value); } //出栈 printf("\n出栈的数字顺序为:\n"); while(s->top != NULL && s->count > 0){ printf("%d\t",list_stack_pop(s)); } system("pause"); return 0; }
原文:http://blog.csdn.net/lofter_h/article/details/19837721