直接看代码:
相同的运行效果:
/*Enter some integers, ending with 02 6 9 12 3 0Numbers in reverse order3 12 9 6 2*/
我们知道,我们构建程序,特别是大型程序,如同构建一幢建筑物,可以使用构建块,程序的构建块可以是函数,也可以是类对象。如上,相同的问题,可以用面向过程的函数块来构建,也可以用面向对象的对象块来构建,对比一下,对象块的封装性与独立性更强,特别是面对大型程序,面对更复杂的问题,对象之间的继承、组合、依赖、联合、包含等关系可以通过不同的设计模式去实现。
附代码1
#include #include #define RogueValue -9999#define MaxStack 10typedef struct stack{int top;int ST[MaxStack];}StackType, *Stack;Stack initStack();int empty(Stack);void push(Stack, int);int pop(Stack);int top(Stack);Stack initStack() {Stack sp = (Stack) malloc(sizeof(StackType));sp -> top = -1;return sp;}int empty(Stack S) {return (S -> top == -1);}void push(Stack S, int n) {if (S -> top == MaxStack - 1) {printf("Stack Overflow");exit(1);}++(S -> top);S -> ST[S -> top]= n;}int pop(Stack S) {if (empty(S)) return RogueValue;int hold = S -> ST[S -> top];--(S -> top);return hold;}int top(Stack S) {if (empty(S)) return RogueValue;int hold = S -> ST[S -> top];return hold;}int main() {int n;Stack S = initStack();printf("Enter some integers, ending with 0");scanf("%d", &n);while (n != 0) {push(S, n);scanf("%d", &n);}printf("%d",top(S));printf("Numbers in reverse order");while (!empty(S))printf("%d ", pop(S));system("pause");printf("");}
附代码2
#include #include #define RogueValue -9999#define MaxStack 10class Stack{int top;int ST[MaxStack];public:Stack();int empty();void push(int);int pop();int getTop();};Stack::Stack() {top = -1;}int Stack::empty() {return (top == -1);}void Stack::push(int n) {if (top == MaxStack - 1) {printf("Stack Overflow");exit(1);}++(top);ST[top]= n;}int Stack::pop() {if (empty()) return RogueValue;int hold = ST[top];--(top);return hold;}int Stack::getTop() {if (empty()) return RogueValue;int hold = ST[top];return hold;}int main() {int n;Stack s;printf("Enter some integers, ending with 0");scanf("%d", &n);while (n != 0) {s.push(n);scanf("%d", &n);}printf("Numbers in reverse order");while (!s.empty())printf("%d ", s.pop());system("pause");printf("");} /*Enter some integers, ending with 02 6 9 12 3 0Numbers in reverse order3 12 9 6 2*/
-End-