您的位置:首页 > 其它

自定义Stack

2015-07-05 11:00 232 查看
某些情况下,不能使用STL,那么就需要自定义栈,实现如下:

1.模板方法实现方式

栈的主要实体是一个单链表,每次入栈把结点插入表头,每次出栈删除表头结点

/*
*	自定义栈
*/
template<class T>
struct Stack {
T node;
Stack* next;
};

template<class T>
void initStack(Stack<T> **s) {
*s = new Stack<T>();
(*s)->next = NULL;
}

template<class T>
void push(Stack<T> *s, T t) {
Stack<T> *n = new Stack<T>();
n->node = t;
n->next = s->next;
s->next = n;
}

template<class T>
T pop(Stack<T> *s) {
if (s->next != NULL) {
Stack<T> *t = s->next;
s->next = t->next;
T ret = t->node;
delete t;
return ret;
}
return NULL;
}

template<class T>
bool empty(Stack<T> *s) {
if (s->next != NULL) {
return false;
}
return true;
}

2.模板类实现方式

栈的实体是一个预先分配好的数组,入栈是往数组里加入元素,index后移;出栈是取出index位置元素,index前移。另外由于是预先分配大小,出现不够用的情况,则自动增加一倍大小size。

template<class T>
class Stack {
public:
Stack(){
data = new T[1];
capacity = 1;
top = -1;
}
void push(T t) {
if (top+1 == capacity) {
capacity *= 2;
T* n = new T[capacity];
if (n == NULL) {
return;
}
for(int i=0; i<=top; ++i) {
n[i] = data[i];
}
data = n;
}
data[++top] = t;
}
T pop() {
T ret = data[top];
--top;
return ret;
}
bool empty() {
if (top == -1) {
return true;
}
return false;
}
public:
T* data;
int top;
int capacity;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: