动态数组实现:
#define CURL_STATICLIB
# include<iostream>
# include<string>
#include<assert.h>
using namespace std;
template<typename T>
class Mystack
{
private:
T* arr;
int _count;
int cap;//容量
int length;
public:
Mystack<T>()
{
this->cap = 1024;
_count = 0;
arr = new T[cap];
length = 0;
}
Mystack<T>(int cap)
{
this->cap = cap;
_count = 0;
arr = new T[cap];
length = 0;
}
~Mystack()
{
delete[]arr;
}
void push(T val)
{
assert(_count < cap);//假如为真就不会报错,避免越界限访问
arr[_count] = val;
++_count;
++length;
}
T pop()
{
assert(length>0);
--length;
return arr[--_count];
}
T top()
{
return arr[_count-1];//return arr[_count-1]
}
bool empty()
{
return length == 0;
}
int size()
{
return length;
}
int capacity()
{
return cap;
}
T get_count(int num)
{
return arr[num];
}
};
int main()
{
Mystack<string>s;
s.push("abc");
s.push("def");
s.push("ghi");
s.push("jkl");
s.push("mno");
int len = s.size();
for (int i = 0; i <len; i++)
{
cout << s.top() << endl;
s.pop();
}
if (s.empty())
{
cout << "I like coding" << endl;
}
return 0;
}
链表实现:
1.在入栈的过程中,用到反插法;
即在头节点和第一个节点之间进行填充元素:
temp->next = topNode;
topNode = temp;//用头插法实现链表的内置
2.头插法和尾插法
//尾插法
rear->next=newNode
rear=rear->next
//头插法
temp->next=head->next
head->next=temp
完整代码:
#define CURL_STATICLIB
# include<iostream>
# include<string>
#include<assert.h>
using namespace std;
template<typename T>
class Node
{
public:
Node<T>* last;
Node<T>* next;
T val;
Node(T val) :val(val), next(NULL), last(NULL) {}
~Node() { delete next; delete last; }
};
template <typename T>
class Mystack
{
private:
Node<T>* topNode;
int _size;
public:
Mystack() :topNode(NULL), _size(0) {}
~Mystack() { delete topNode; }
void push(T x)
{
if (NULL == topNode) { topNode = new Node<T>(x); topNode->last = NULL; ++_size; return; }
Node<T>* temp = new Node<T>(x);
temp->next = topNode;//反插法
topNode = temp;
//temp->next=topNode;topNode=temp;
//rear->next=newNode;rear=rear->next 队列和栈的pop()都是基于位置的移动 先插入后确定位置移动
//newNode->next=head->next;
//head->next=newNode;
}
void pop()
{
assert(NULL != topNode);
Node<T>* temp = topNode;
topNode = topNode->next;
--_size;
}
T top()
{
assert(NULL != topNode);
return topNode->val;
}
void size()
{
return _size;
}
bool empty()
{
return topNode == NULL;
}
};
int main()
{
Mystack<string>s;
s.push("passion");
s.push("optimistic");
s.push("Tencent");
while (!s.empty())
{
cout << s.top() << endl;
s.pop();
}
}