This project is about to realize a Stack based on C++11.
When I trying to complie this project, there are something wrong and I don't know why.
- Here are the codes:
Stack.h
#include<iostream>
using std::size_t;
template <typename T>
struct Node {
Node* next;
T data;
Node(T arg = 0) :data(arg), next(nullptr) { }
};
template <typename T>
class Stack {
public:
Stack() :head(new Node<T>()), size(0) { }
~Stack();
Stack& operator=(const Stack&);
Stack(const Stack&);
bool push(const T&);
bool pop();
const T get_top();
bool isEmpty();
Node<T>* begin();
Node<T>* end();
private:
Node<T>* head;
size_t size;
Node<T>* getEnd();
Node<T>* getBeforeEnd();
void free();
void copy_from(const Stack&);
};
Stack.cpp
#include"Stack.h"
template<typename T>
Node<T>* Stack<T>::begin()
{
if (head->next)
return head->next;
else
return nullptr;
}
template<typename T>
Node<T>* Stack<T>::end()
{
return getEnd()->next;
}
template<typename T>
Node<T>* Stack<T>::getEnd()
{
if (!head->next)
return nullptr;
Node<T> *end = head->next;
while (end->next)
end = end->next;
return end;
}
template<typename T>
Node<T>* Stack<T>::getBeforeEnd()
{
int num = 0;
auto* p = head;
while (num < size - 1)
{
p = p->next;
++num;
}
return p;
}
template<typename T>
void Stack<T>::free()
{
Node<T>* end = getEnd();
while (end != head)
{
Node<T>* temp = head;
head = head->next;
delete temp;
}
delete head;
size = 0;
}
template<typename T>
Stack<T>::~Stack<T>()
{
free();
}
template<typename T>
void Stack<T>::copy_from(const Stack<T>& rhs)
{
Node<T>* Head = new Node<T>;
auto* First = Head;
auto* beg = rhs.begin();
while (beg != rhs.end())
{
Node<T>* Next = new Node<T>;
Next->data = beg->data;
Head->next = Next;
Head = Next;
beg = beg->next;
}
this->head = First;
this->size = rhs.size;
}
template<typename T>
Stack<T>& Stack<T>::operator=(const Stack& rhs)
{
if (&rhs != this)
{
free();
copr_from(rhs);
}
return *this;
}
template<typename T>
Stack<T>::Stack(const Stack& s)
{
free();
copy_from(s);
size = s.size;
}
template<typename T>
bool Stack<T>::push(const T& e)
{
auto* end = getEnd();
Node<T>* tail = new Node<T>;
tail->data = e;
end->next = tail;
++size;
return true;
}
template<typename T>
bool Stack<T>::pop()
{
auto* p = getBeforeEnd();
auto* temp = p->next;
p->next = nullptr;
delete temp;
size -= 1;
return true;
}
template<typename T>
const T Stack<T>::get_top()
{
const T e = getEnd()->data;
return e;
}
template<typename T>
bool Stack<T>::isEmpty()
{
return (head->next) ? true : false;
}
Main
#include"Stack.h"
#include<string>
#include<iostream>
using namespace std;
int main()
{
Stack<string> s;
string word;
while (cin >> word)
s.push(word);
while (!s.isEmpty())
{
cout << s.get_top() << endl;
s.pop();
}
return 0;
}
I use VS2017 to complie this project, here are the complie errors:
Aucun commentaire:
Enregistrer un commentaire