您好,登錄后才能下訂單哦!
棧:具有先進后出的特點,且只能在一端進行插入與刪除的操作,棧的實現如下所示
struct truetype
{
bool get()
{
return true;
}
};
struct falsetype
{
bool get()
{
return false;
}
};
template<class T>
struct typetraits
{
typedef falsetype isnpodtype;
};
template <>
struct typetraits<int>
{
typedef truetype ispodtype;
};
template<class T>
class stack
{
protected:
T *_a;
size_t _top;
size_t _capacity;
public:
stack()
: _top(0)
, _capacity(3)
{
_a = new T[_capacity];
}
~stack()
{
if (_a)
delete[] _a;
}
void checkcapacity()
{
if (_top == _capacity)
{
_capacity = 2 * _capacity;
T *tem = new T[_capacity];
if ((typetraits<T>::ispodtype()).get())
{
memcpy(tem, _a, sizeof(T)*_capacity);
delete[]_a;
_a = tem;
}
else
{
int i = 0;
for (i = 0; i < _top; i++)
{
tem[i] = _a[i];
}
delete[]_a;
_a = tem;
}
}
}
void push(const T&x)
{
checkcapacity();
_a[_top] = x;
_top++;
}
void pop()
{
_top--;
}
bool Empty()
{
return _top == 0;
}
T &Top()
{
if (_top > 0)
{
size_t ret = _top;
_top--;
return _a[ret - 1];
}
}
};
int main()
{
stack<int> s1;
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
while (!s1.Empty())
{
cout << s1.Top() << " ";
}
getchar();
return 0;
}
2.隊列:具有隊頭插入,隊尾刪除的特點,具有一個頭指針和一個尾指針
template <class T>
struct Node
{
T _data;
Node <T> *_next;
Node(const T &data=0)
{
_data = data;
_next = NULL;
}
};
template <class T>
class Queue
{
protected:
Node<T> *_head;
Node <T>*_tail;
public:
Queue()
:_head(NULL)
, _tail(NULL)
{}
~Queue()
{
Node<T> *ret = NULL;
if (_head == NULL)
return;
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = _head;
}
else
{
while (_head)
{
pop();
}
}
}
void push(const T&x)
{
Node<T> *newNode = new Node<T>(x);
if (_tail == NULL)
{
_tail = newNode;
_head = _tail;
}
else
{
_tail->_next = newNode;
_tail = newNode;
}
}
void pop()
{
Node<T>*ret = NULL;
if (_head == NULL)
return;
if (_head == _tail)
{
delete _head;
_head = NULL;
_tail = _head;
}
else
{
ret = _head;
_head = _head->_next;
delete ret;
}
}
T &Front()
{
Node <T>*ret = _head;
_head = _head->_next;
return ret->_data;
}
T &Back()
{
Node <T>*ret = _tail;
_tail = _head->_tail;
return _tail->_data;
}
bool Empty()
{
return _head == _tail;
}
void show()
{
while (_head)
{
cout << _head->_data << " ";
_head = _head->_next;
}
}
};
int main()
{
Queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.pop();
q.show();
getchar();
return 0;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。