《算法导论》数据结构那一章节的练习。
方法一:
使用静态数组
#include<stdio.h> int SS[10];//定义一个数组作为stack int top=0;//定义stack的指针 bool STACK_EMPTY()//判断stack是否为空 { if(top==0) return true; else return false; } void PUSH(int *S,int x)//入栈操作 { top=top+1; S[top]=x; } int POP(int *S)//出栈操作 { if(STACK_EMPTY())//如果栈为空,则返回-1 return -1; else//如果栈不为空,则指针向前退1,返回当前指针所指向的元素 top=top-1; return S[top+1]; } void main() { //连续压栈,将1,2,3,4,5一次存入栈中。 PUSH(SS,1); PUSH(SS,2); PUSH(SS,3); PUSH(SS,4); PUSH(SS,5); while(top!=0)//如果栈不为空,则执行出栈操作,并输出出栈的元素。 { int p=POP(SS); printf("%d/n",p); } }
方法二:
通过传递数组的引用实现
#include<stdio.h> bool STACK_EMPTY(int &top) { if(top==0) return true; else return false; } void PUSH(int *S,int x,int &top) { top=top+1; S[top]=x; } int POP(int *S,int &top) { if(STACK_EMPTY(top)) return -1; else top=top-1; return S[top+1]; } void main() { int SS[10]; int top=0; PUSH(SS,1,top); PUSH(SS,2,top); PUSH(SS,3,top); PUSH(SS,4,top); PUSH(SS,5,top); while(top!=0) { int p=POP(SS,top); printf("%d/n",p); } // printf("hello world!/n"); }