今天回过头来看了看顺序栈的实现,尽管C++使用模板类实现很方便,但是C语言也有一个较为简单的变通的方法;Java实现也比较方便。 (1) C++代码: //C++顺序栈 #include <stdlib.h> #define STACKSIZE 50 template <class T> class STACK { private: T *base; T *top; int size; public: int init(int n); int push(T data); int pop(T *pdata); int gettop(T *pdata); }; template <class T> int STACK<T> :: init(int n) { T *p = (T *)malloc(n * sizeof(T)); if(p == NULL)return 0; base = top = p; size = n; return 1; } template <class T> int STACK<T> :: push(T data) { if(top == base + size)return 0; * top ++ = data; return 1; } template <class T> int STACK<T> :: pop(T *pdata) { if(top == base)return 0; *pdata = * -- top; return 1; } template <class T> int STACK<T> :: peek(T *pdata) { if(top == base)return 0; *pdata = *(top - 1); return 1; } (2) C语言代码 //顺序栈 #include <stdlib.h> #define STACK_SIZE 100 typedef float TYPE; typedef struct stack { TYPE *base;//栈底, 固定值 TYPE *top; int size; }STACK; STACK *init_stack(int n) { STACK *p = (STACK *)malloc(sizeof(STACK)); if(p == NULL) return NULL; p->top = p->base = (TYPE *)malloc(n * sizeof(TYPE)); p->size = n; return p; } int push(STACK *stack, TYPE data) { if(stack->top == stack->base + stack->size) return 0; *stack->top++ = data; return 1; } int pop(STACK *stack, TYPE *data) { if(stack->top == stack->base) return 0; *data = * --stack->top; return 1; } int peek(STACK *stack, TYPE *data) { if(stack->top == stack->base) return 0; *data = * (stack->top - 1); return 1; } (3) Java代码 public class stack { private int base; private int top; private int size; private Object[] data; public stack(){ size = 100; data = new Object[size]; base = top = 0; } public stack(int n){ size = n; data = new Object[size]; base = top = 0; } public int push(Object data){ if(top == base + size)return 0; this.data[top++] = data; return 1; } public int pop(Object data){ if(top == base)return 0; data = this.data[--top]; return 1; } public int peek(Object data){ if(top == base)return 0; data = this.data[top - 1]; return 1; } }